Anton Barinov
Anton Barinov

Reputation: 193

pointer being realloc'd was not allocated char* realloc in function

I am learning pointers now, and i have some troubles with reallocating of char* in function. When i am running this code, i have this error. p.s. the one only goal of this code, it to understand how are pointers working.

void redefine(char** string) {
   *string = realloc(*string, 10 * sizeof(char));
   *string = "otherText";
}

int main(){
   char *first = malloc(5 * sizeof(char));
   first = "text";
   redefine(&first);
   return 0;
}

thanks in forward

Upvotes: 0

Views: 690

Answers (1)

Barmar
Barmar

Reputation: 782344

C doesn't use assignment to copy strings.

When you do

first = "text";

first now points to the literal string text, it no longer points to the memory that was allocated with malloc(). So you can't call realloc() on that pointer.

You should use:

strcpy(first, "text");

to copy the sdtring into the allocated memory.

Similarly, in the function you should use

strcpy(*string, "otherText");

Upvotes: 4

Related Questions