我寫了這個無辜的代碼,並導致這樣一個邪惡的錯誤:從調試(cgdb)輸出malloc.c中的SIGABRT,剛剛發生了什麼?
static char * prefixed(char * pref, char *str) {
size_t newalloc_size = sizeof(char) * (strlen(pref) + strlen(str));
char * result = (char*) malloc(newalloc_size);
[...]
:
Breakpoint 1, prefixed (pref=0x401345 "Env: ", str=0x4012b5 "Home") at ./src/backend/os/env.c:77
(gdb) s
(gdb) p newalloc_size
$1 = 9
(gdb) s
envtest: malloc.c:2368: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >=
(unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)'
failed.
Program received signal SIGABRT, Aborted.
0x00007ffff7a68fd5 in raise() from /usr/lib/libc.so.6
(gdb)
我查了傳遞的參數了。他們正如他們應該是:
Breakpoint 1, prefixed (pref=0x401345 "Env: ", str=0x4012b5 "Home") at ./src/backend/os/env.c:77
(gdb) p pref
$2 = 0x401345 "Env: "
(gdb) p strlen(pref)
$3 = 5
(gdb) p str
$4 = 0x4012b5 "Home"
(gdb) p strlen(str)
$5 = 4
(gdb)
任何人都可以想象,這裏出了什麼問題?我知道有兩種功能可以將兩根弦串在一起,但我想自己做!
親切的問候。
這看起來像堆腐敗。實際的錯誤可能只是在代碼中的任何地方,可能遠離該塊。 – Mat
Libc懲罰你爲'malloc()'返回值。 – 2012-11-01 16:22:51
只是順便說一句:'newalloc_size = ... + 1'允許終止'0' – slashmais