c++ - Realloc char* inside structure -
i'm new c programming, have structure char , int pointer, used modify pointer frequently, found reference in online realloc char* , working fine, same thing when used inside structure mean problem arise,
typedef struct mystruct { int* intptr; char* strptr; } mystruct;
inside main()
mystruct *mystructptr; mystructptr = new mystruct(); mystructptr->intptr = new int(); *mystructptr->intptr = 10; mystructptr->strptr = (char *)malloc(sizeof("original")); mystructptr->strptr = "original"; printf("string = %s, address = %u\n", mystructptr->strptr, mystructptr->strptr); mystructptr->strptr = (char *)realloc(mystructptr->strptr, sizeof("modified original")); mystructptr->strptr = "modified original"; printf("string = %s, address = %u\n", mystructptr->strptr, mystructptr->strptr);
i found following error while reallocating char* inside pointer
this may due corruption of heap, indicates bug in or of dlls has loaded.
the problem here is, after allocating memory
mystructptr->strptr = (char *)malloc(sizeof("original"));
you're overwriting returned pointer
mystructptr->strptr = "original";
and then, try use realloc()
on pointer not returned memory allocator function. causes undefined behavior.
quoting c11
, chapter §7.22.3.5
if
ptr
null pointer,realloc
function behavesmalloc
function specified size. otherwise, ifptr
not match pointer earlier returned memory management function, or if space has been deallocated callfree
orrealloc
function, the behavior undefined. [....]
that said, should never use %u
print pointer itself, youust use %p
format specifier , cast teh corresponding argument (void *)
.
solution should either
Comments
Post a Comment