0

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?

Dilip Kumar
  • 1,736
  • 11
  • 22
tomol
  • 755
  • 1
  • 6
  • 12
  • `char* op, op_temp` and `char *op, op_temp` are the same. That's why I don't put `*` next to the type name (easier to expect that both `op` and `op_temp` will be pointers). – woytaz Jan 29 '15 at 10:38
  • @woytaz Yes, you're right. Sorry for the mistake. In my head, I wanted to say that `char *op, op_temp` is clear because the asterisk is attached to the variable while `char* op, op_temp` is ambiguous because it looks like `char *` will apply to both variables. – Chostakovitch Jan 29 '15 at 10:46

4 Answers4

3

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

char *op, *op_temp;

or

char* op;
char* op_temp;
myaut
  • 11,174
  • 2
  • 30
  • 62
3

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;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Dilip Kumar
  • 1,736
  • 11
  • 22
0

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;
woytaz
  • 86
  • 5
0

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.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46