Question

Lets say I have the following situation (some rough pseudocode):

struct { 
  int i;
} x

main(){
  x** array = malloc(size of x pointer); // pointer to an array of pointers of type x
  int* size = current size of x // (initally 0)
  add(array, size);
}

add(x** array, int* size){ // adds one actual element to the array
  x** temp = realloc(array, (*size)+1); // increase the array size by one
  free(array);
  array = temp;

  // My question is targeted here
  array[*size] = malloc(size of x); // makes a pointer to the value 
  array[*size]->i = size;
  *size++;  
}

My question is: Once add() is finished, do the values of the pointers stored in array disappear along with the function call stack, since I allocated them inside func()? I fear that they might, in which case would there be a better way for me to do things?

Was it helpful?

Solution

No, they don't. They persist until the pointer returned by malloc() is passed to the corresponding free() function. There would be no point in the existence of the malloc() function if it worked the same way as automatic arrays.

Edit: sidenote. As @Ancurio pointer it out, you're incorrectly freeing the memory behind the previous pointer returned by malloc() which is at that time invalid as realloc() has been used on it. Don't do that. realloc() does its job properly.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top