0
int i=0;
float *array;
while(i<20)
{   
    array=realloc(array,((i+1)*sizeof(float)));
    i++;
}

Whats wrong with this code?

    array=realloc(array,((i+1)*sizeof(float)));

This line gives sigtrap.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • 8
    You are calling `realloc` with an **uninitialized** argument (`array`) on the first loop. Set that to `NULL` in the declaration: `float *array = NULL;`. – Adrian Mole May 24 '20 at 13:02
  • This is also a worthwhile read: https://stackoverflow.com/q/38213123/10871073 – Adrian Mole May 24 '20 at 13:11
  • Is this just an experiment or part of production code? If it is the latter, this code should be replaced as the reallocation at each iteration has no use actually. – RobertS supports Monica Cellio May 24 '20 at 13:11
  • [This](https://stackoverflow.com/a/12134328/11336762) answer is relevant too, in case @Adrian wants to write its answer. (TLDR: realloc with or without a NULL pointer as a parameter) – Roberto Caboni May 24 '20 at 13:29
  • 1
    Compiler warnings can catch this. `-O -Wall` for gcc, `-O -Wconditional-uninitialized` for clang. – Nate Eldredge May 24 '20 at 13:56

1 Answers1

0

You don't show it (this is the reason we recommend you to post a minimal, verifiable and complete example) but the most probable reason for it to give you an exception is:

  • your array pointer is automatic (this is, declared inside a function body or an inner block, not a global variable)
  • you don't initialize it, so it has any value.
  • If you pass NULL to realloc(), then realloc tries to allocate a completely new block, but if you pass something different than NULL it consider it represents an already allocated block (which it isn't) and the computer explodes.

Just change your declaration:

float *array;

to

float *array = NULL;

and rerun.

Note

It is very important you post a complete example, because if you don't we have to guess what you could have done. In your example, should the variable had been defined as a global variable (out of any functions) then it should have been initialized as NULL, and your bug had gone away. In this case, trying to focus us in the realloc() function, you have just eliminated the bug, making us to try and guess.

Community
  • 1
  • 1
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31