user1298016
user1298016

Reputation: 1021

realloc not working

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

Answers (4)

David Heffernan
David Heffernan

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

dexametason
dexametason

Reputation: 1133

First you have to use malloc to allocate memory. After that you should use

p = realloc(a, 10 *sizeof(char))

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300759

You can't realloc memory that wasn't alloc'ed via malloc, calloc (or similiar dynamic memory allocation function).

Upvotes: 2

Mat
Mat

Reputation: 206859

You can't realloc memory you didn't (originally) get via malloc, it's as simple as that.

Upvotes: 2

Related Questions