The new code still leaks the original allocation if the realloc fails. I expect most implementations won't ever fail to shrink a block, but it's allowed. The correct way to call realloc, whether growing or shrinking the block, is void *tmp = realloc(myPointer, 50*sizeof(int)); if (!tmp) { /* handle error somehow. myPointer still points to the old block, which is still allocated */ } myPointer = tmp;. – Steve Jessop 48 mins ago
Hey, I couldn't figure out how to reply to your comment, sorry.
Do I need to cast tmp to the type of myPointer? In this case, do I need to write
myPointer = (int*)tmp
Also, in this case, when I do
free(myPointer)
The memory pointed at by tmp will be freed as well, right? So no need to do
free(myPointer)
free(tmp)
realloc
and hence you can't possibly free it. But as R..'s answer indicates, you might have got lucky on an implementation detail. – Bradburyrealloc
fails. I expect most implementations won't ever fail to shrink a block, but it's allowed. The correct way to call realloc, whether growing or shrinking the block, isvoid *tmp = realloc(myPointer, 50*sizeof(int)); if (!tmp) { /* handle error somehow. myPointer still points to the old block, which is still allocated */ } myPointer = tmp;
. – Bradbury