Reputation: 1021
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;
}
Upvotes: 1
Views: 2399
Reputation: 613461
You must pass to realloc
a pointer to memory allocated by malloc
or one of its friends. In your code you are passing a
which 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.
Upvotes: 5
Reputation: 1133
First you have to use malloc to allocate memory. After that you should use p = realloc(a, 10 *sizeof(char))
Upvotes: 0
Reputation: 300759
You can't realloc memory that wasn't alloc'ed via malloc
, calloc
(or similiar dynamic memory allocation function).
Upvotes: 2
Reputation: 206859
You can't realloc
memory you didn't (originally) get via malloc
, it's as simple as that.
Upvotes: 2