realloc ------ expand the memory space obtained by malloc

char* p = malloc(1024);
char* q = realloc(p,2048);

The question now is how we should handle pointer p. I just started in accordance with the most intuitive understanding, if that is directly p = NULL ;. Finally, just to free up space q on it.

Because recently to be a package. The results showed that when doing unit tests. Sometimes I free (q); when an error occurs. So I was depressed.

Later, carefully tracking, after the discovery of p and q realloc finished pointer address is the same. But sometimes not the same.

Carefully check the following information. Get the following information:

       1. If the current block of contiguous memory realloc enough, except that the p points to expand the space, and returns a pointer to the address p. This time p and q point to address is the same.

       2. If the current is not enough contiguous memory block length, long enough to find a place, a new memory allocation, q, and p at the copy content to q, return q. And p points to delete the memory space.

Sometimes this means that realloc will sometimes produce a new memory address does not. Therefore, upon completion of the assignment. We need to determine at p is equal to q. And handled accordingly.

Bit is to be noted here is to avoid p = realloc (p, 2048); this wording. After realloc may cause allocation failure, p originally at the memory address is missing.

Guess you like

Origin www.cnblogs.com/god-of-death/p/11334846.html