Is there an __attribute __ ((ns_returns_retained)) equivalent for a malloc'd pointer?

I'm looking for an annotation something like

-(SomeStruct *) structFromInternals __attribute__((returns_malloced_ptr)) { SomeStruct *ret = malloc(sizeof(SomeStruct)); //do stuff return ret; } 

to reassure the beast of a static clan analyzer. The only viable link I can find is for GCC , but it doesn't even include ns_returns_retained , which is in the extension, I suppose.

EDIT:

why it is necessary, I have a script that I can not reproduce in the simple case, so it can be related to ac lib in the Objective-C project ... The bottom line is that I get a static analyzer that warns about the leak of malloc in createStruct:

 typedef struct{ void * data; size_t len; }MyStruct; void destroyStruct(MyStruct * s) { if (s && s->data) { free(s->data); } if (s) { free(s); } } MyStruct * createStructNoCopy(size_t len, void * data) { MyStruct * retStruct = malloc(sizeof(MyStruct)); retStruct->len = len; retStruct->data = data; return retStruct; } MyStruct * createStruct(size_t len, void * data) { char * tmpData = malloc(len); memcpy(tmpData, data, len); return createStructNoCopy(len, tmpData); } MyStruct * copyStruct(MyStruct * s) { return createStruct(s->len, s->data); } 
+6
source share
1 answer

The annotation of the ownership_returns(malloc) function will tell the Clang static analyzer that the function returns a pointer that should be passed to free() at some point (or in a function with ownership_takes(malloc, ...) ). For instance:

 void __attribute((ownership_returns(malloc))) *my_malloc(size_t); void __attribute((ownership_takes(malloc, 1))) my_free(void *); ... void af1() { int *p = my_malloc(1); return; // expected-warning{{Potential leak of memory pointed to by}} } void af2() { int *p = my_malloc(1); my_free(p); return; // no-warning } 

(See the malloc-annotations.c test file for some examples of their use.)

Currently, these annotations take effect only when the alpha.unix.MallocWithAnnotations check is alpha.unix.MallocWithAnnotations (which is not executed by default). If you use Xcode, you need to add -Xclang -analyzer-checker=alpha.unix.MallocWithAnnotations to your build flags.

+5
source

Source: https://habr.com/ru/post/943900/


All Articles