struct line {
int length;
char contents[0];
}
int this_length = 60;
struct line *thisline = (struct line *)malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
struct line {
int length;
char contents[60];
}
printf ("thisline 指向的地址为 %p\n", thisline);
printf ("thisline指向的第一个元素值为:%d\n",thisline->length);
printf ("该元素的地址为%p\n", &thisline->length);
printf ("%p\n", &thisline->contents);
printf ("%p\n", &thisline->contents[0]);
printf ("%p\n", &thisline->contents[1]);
thisline 指向的地址为 0x8780008
thisline指向的第一个元素值为:60
该元素的地址为0x8780008
0x878000c
0x878000c
0x878000d
char c = 'x';
int i;
thisline->contents[0] = c;
c = 'y';
thisline->contents[1] = c;
c = 'z';
thisline->contents[2] = c;
for (i = 0; i < 3; i++)
printf ("%c\n", thisline->contents[i]);
struct line *thisline_bak = thisline;
free(thisline);
printf ("%d\n", thisline_bak->length);
for (i = 0; i < 3; i++)
printf ("%c\n", thisline->contents[i]);
free (thisline->contents);
*** glibc detected *** ./array4: free(): invalid pointer: 0x09e4300c ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x5b8591]
/lib/tls/i686/cmov/libc.so.6(+0x6cde8)[0x5b9de8]
/lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0x5bcecd]
./array4[0x80485ad]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x563bd6]
./array4[0x80483c1]
======= Memory map: ========
... ...
free (thisline->contents); /*先释放掉后面的数组buffer*/
free(thisline); /*再释放掉 4 字节整型空间*/
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |