Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS removes allocated memory in native library

Strange behavior in IOS while integrating with a c/c++ library.

In AppDelegate i call

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^{
    [[ABCService sharedInstance] abcInitialize];
});

abcInitialize is defined in c++ library

struct abc *top;
top = calloc(TYPE_SERV,size_of(struct abc));
top->us = server_alloc (...certain_params...);

inside server alloc i do alloc of structures struct1 and struct2 And then in Initialize function i try to access

top->us = calloc(TYPE_US, size_of(struct us));
if(top->us->struct1) //do something

I noticed that my struct1 is always null

When i debugged, i can see that the structure was allocated fine and values are set appropriately, but before returning from the function, the memory is automatically deallocated. This is totally confusing and annoying. Could any one help me understand what is going on?

I tried by turning off ARC too, still no change

like image 654
blganesh101 Avatar asked Jul 25 '15 07:07

blganesh101


2 Answers

top->us = calloc(TYPE_US, size_of(struct us));
if(top->us->struct1) //do something 

I noticed that my struct1 is always null

If that's your real code, then yes, struct1 will always be null. calloc allocates memory and initializes it to zero. Hence, all of the members of top->us will be zero, and since struct1 is a member of top->us, it's going to be zero, i.e. NULL.

like image 87
user3386109 Avatar answered Oct 06 '22 04:10

user3386109


First of all, ARC has nothing to do with memory management of C or C++ codes, so, you can rule out ARC for causing this.

According to http://www.cplusplus.com/reference/cstdlib/calloc/, calloc always initialize all the bits of the allocated memory to 0, naturally, top->us->struct1 will be NULL.

but before returning from the function, the memory is automatically deallocated

How do you come to the conclusion that the memory is automatically deallocated? As mentioned above, ARC will not automatically release your C++ structure/object.

As a conclusion. The result you saw was indeed as expected.

like image 27
utogaria Avatar answered Oct 06 '22 06:10

utogaria