简体   繁体   中英

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

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.

With information available this can't be answered, but let me try.

The code seems ok. I can't reproduce your problem either.

You can't really put a breakpoint on a blank line. I guess that would put it on a line with free.

My guess is, your code was compiled with optimization enabled, which probably reordered things making sure you are not really sure where execution has stopped. Disable optimization and re-build (on GCC that would be -O0). Or show us the disassembly (including current PC where you print).

My run on Ubuntu gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4 built with -O0 -g, stopped on a line with free (before it was executed):

(gdb) print i
$1 =
(gdb) set $pos=0
(gdb) print P_i[$pos++]
$2 = (float *) 0x602040
(gdb) print P_i[$pos++]
$3 = (float *) 0x602060
(gdb) print P_i[$pos++]
$4 = (float *) 0x602080
(gdb) print P_i[$pos++]
$5 = (float *) 0x6020a0
(gdb) bt
#0 main () at malloc.c:12
(gdb) list
7 for(i=0;i<6;i++)
8 {
9 float** P_i=(float**) malloc(4*sizeof(float*));
10 for(a=0;a<4;a++) P_i[a]=(float*) calloc(4,sizeof(float));
11
12 for(a=0;a<4;a++) free(P_i[a]);

Does your source code exhibit a problem even if you build it separately (not a part of larger program)? Do you have custom calloc / malloc implemented? What does "nm your-executable|grep calloc" show? It should be something like this:

U calloc@@GLIBC_2.2.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM