Search code examples
c++memory-managementrealloc

Question on using realloc implementation in C++ code


Friends

In our C++ , Iam current using realloc method to resize the memory allocated by malloc. realloc() usage is done as below

my_Struct *strPtr =(my_struct*)malloc(sizeof(my_Struct));

/* an later */

strPtr = (my_struct*)realloc(strPtr,sizeof(my_Struct)*NBR);

now wikipeadia (_http://en.wikipedia.org/wiki/Malloc)says that

If instead one did

void *p = malloc(orig_size);

/* and later... */

p = realloc(p, big_size);

then in case it is not possible to obtain big_size bytes of memory, p will have value NULL and we no longer have a pointer to the memory previously allocated for p, creating a memory leak

And it also says that the correct way to rectify the above error is

void *p = malloc(orig_size);

/* and later... */

void *tmp = realloc(p, big_size); 

if (tmp != NULL)
 {

p = tmp; /* OK, assign new, larger storage to p */

} 

else 

{

/* handle the problem somehow */

}

Can you tell me which is the best way to use realloc()

also once I have pointer to a structure and then while using realloc later can i use pointer to a void ???

Many Thanks


Solution

  • Of course you must protect against the case that realloc() returns NULL. It is a memory allocation, and in C (where realloc()) is mostly used, I think C++ programmers think it is a bit low-level/qaint to use raw realloc() calls, memory allocations can always fail.

    Directly overwriting the pointer with the return value is an error, as that drops the original pointer and makes the memory leak in case the reallocation failed.