I have to allocate memory for 4 pointers to pointers on float (2D) over many iterations (6), but at the second iteration, malloc gives me the same address for two allocations. Code :
int i=0, a=0;
for(i=0;i<6;i++)
{
float** P_i=(float**) malloc(4*sizeof(float*));
for(a=0;a<4;a++) P_i[a]=(float*) calloc(4,sizeof(float));
for(a=0;a<4;a++) free(P_i[a]);
free(P_i);
}
Debugging with gdb :
(gdb) print i
$42 = 1
(gdb) set $pos=0
(gdb) print P_i[$pos++]
$51 = (float *) 0x804d500
(gdb) print P_i[$pos++]
$52 = (float *) 0x804d148
(gdb) print P_i[$pos++]
$53 = (float *) 0x804d4e8
(gdb) print P_i[$pos++]
$54 = (float *) 0x804d500
P_i[0] and P_i[3] point to the same address 0x804d500 and I can't find why :/
If the malloc function is unable to allocate the memory buffer, it returns NULL. Any normal program should check the pointers returned by the malloc function and appropriately handle the situation when memory could not be allocated.
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void , use a type cast on the return value.
The most likely causes are writing outside the bounds of an allocated object, or writing to an object after it has been deleted. These errors can be difficult to track down with a debugger.
malloc(n) returns NULL on failure. malloc(0) may return NULL . To detect failure: void* ptr = malloc(n); if (ptr == NULL && n > 0) Handle_Failure();
between the first for(a=0;a<4;a++) and the 2nd (before freeing)
My guess is that gdb breaks on last iteration of the loop, before the last calloc() call. If it's the case P_i[3] have the address of the previous iteration.
Btw, it's hard to use gdb when there's more than one statement per line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With