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
.
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
.
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:
array
pointer is automatic (this is, declared inside a function body or an inner block, not a global variable)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.
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.