Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected results for memory allocation with c malloc function

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 :/

like image 223
DahoM Avatar asked May 17 '16 10:05

DahoM


People also ask

What happens if malloc Cannot allocate memory?

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.

What does function malloc () return on error?

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.

What causes malloc error?

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.

How do I know if malloc failed?

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();


1 Answers

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.

like image 145
mgagnon Avatar answered Nov 15 '22 08:11

mgagnon