I am trying to understand how realloc works. This is my program. It’s giving some strange errors. Can anyone help me? I am just trying to do realloc for the array a. Any help appreciated.
#include<stdio.h>
int main()
{
char a[5]="abcd";
char *p;
p = realloc(a,10);
strcpy(a,"abcdefghi");
printf("%s", a);
return 0;
}
You must pass to
realloca pointer to memory allocated bymallocor one of its friends. In your code you are passingawhich is a stack allocated variable.Note that you cannot modify the size of stack allocated data so if your code does need to modify the size of a variable then that variable must be allocated on the heap.