0

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?

Rafik Bouloudene
  • 565
  • 3
  • 13
  • 2
    You cannot `realloc` a string literal. The pointer needs to either be a null-pointer or point to memory allocated by another suitable allocation function (e.g.: `malloc`) – UnholySheep Nov 30 '21 at 18:36
  • 2
    @Rafik Bouloudene You can reallocate only what was allocated with malloc, calloc and realloc. – Vlad from Moscow Nov 30 '21 at 18:37
  • 2
    You may only pass a pointer to `realloc` that was returned by `malloc`, `calloc` or `realloc` ealier. – Gerhardh Nov 30 '21 at 18:37

1 Answers1

0

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:

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128