Search code examples
crealloc

Realloc function returning a null pointer when manipulating strings


i've been trying some stuff with the realloc function and ran into a problem with strings:

char *s="hello";

s=realloc(s,size); // this return null

char *p;
p=malloc(5);

strcpy(p,"hello");

p=realloc(p,size) // this works fine

why does the first declaration fail?


Solution

  • This line declares s and reserves some static storage space for "hello", then assigns a pointer to it to s.

    char *s="hello";
    

    This second line is trying to realloc memory that was never dynamically allocated. In fact, it's static.

    s=realloc(s,size); // this return null
    

    No wonder it fails. Actually, it could very well crash your program, it's undefined behavior! You can only use realloc or free on memory that was previously returned by a call to malloc (or variants). Nothing else.

    See also: