tomol
tomol

Reputation: 763

Why realloc fails with temporary pointer

The following works successfully:

char *op, op_temp;
op = malloc(len+1);
op_temp = op;
op = realloc(op, ++len);

while the following results in a runtime error:

char *op, op_temp;
op = malloc(len+1);
op_temp = op;
op = realloc(op_temp, ++len);

Why so even though the same piece of memory is reallocated?

Upvotes: 0

Views: 121

Answers (4)

Dilip Kumar
Dilip Kumar

Reputation: 1746

As per the man page of realloc()

void *realloc(void *ptr, size_t size);

so, the first argument should be a char *.

OTOH, in your code,

op = realloc(op, ++len);

Here op is of type char *, which is valid. But

op = realloc(op_temp, ++len);

here op_temp is of type char.

Change

char *op, op_temp;

to

char *op  = NULL, *op_temp = NULL;

Upvotes: 3

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12678

I would suggest to use typedef's to eliminate such errors as they encode correct pointer types as explained below:

typedef char *charp;
charp op, op_temp;

NOw the above op & op_temp declared as pointers o type char.

Upvotes: 0

woytaz
woytaz

Reputation: 86

This is because op_temp is not a pointer. You have to put the asterisk * next to each variable name that you want to be a pointer. Like this:

char *op, *op_temp;

Upvotes: 0

myaut
myaut

Reputation: 11514

op_temp is not a pointer, just a char value. You should write:

char *op, *op_temp;

or

char* op;
char* op_temp;

Upvotes: 3

Related Questions