Yes, cptr
will become invalid as realloc moves the block! And no, there is no mention of signalling to you to tell that it is moving the block of memory. By the way, your code looks iffy...read on... please see my answer to another question and read the code very carefully on how it uses realloc
. The general consensus is if you do this:
void *ptr = malloc(1024);
/* later on in the code */
ptr = realloc(ptr, 4096);
/* BAM! if realloc failed, your precious memory is stuffed! */
The way to get around that is to use a temporary pointer and use that as shown:
void *ptr = malloc(1024);
/* later on in the code */
void *tmp = realloc(ptr, 4096);
if (tmp != null) ptr = tmp;
Edit: Thanks Secure for pointing out a gremlin that crept in when I was typing this earlier on.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…