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 behaves malloc function specified size. otherwise, if ptr not match pointer earlier returned memory management function, or if space has been deallocated call free or realloc 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

  • after malloc(), use strcpy() copy content into allocated memory region, pointed returned pointer malloc() call.
  • get rid of malloc() , use non-standard strdup().

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -