C语言 为什么我会在这里得到 SIGABRT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2334352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get a SIGABRT here?
提问by Thomas Pornin
I have this code segment in which I am opening/closing a file a number of times (in a loop):
我有这个代码段,我在其中多次打开/关闭文件(在循环中):
for(i=1;i<max;i++)
{
/* other code */
plot_file=fopen("all_fitness.out","w");
for (j=0;j<pop_size;j++)
fprintf(plot_file, "%lf %lf\n",oldpop[i].xreal[0],oldpop[i].obj);
fclose(plot_file);
/*other code*/
}
I get a SIGABRT here, with the following backtrace:
我在这里得到一个 SIGABRT,回溯如下:
#0 0x001fc422 in __kernel_vsyscall ()
#1 0x002274d1 in *__GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2 0x0022a932 in *__GI_abort () at abort.c:92
#3 0x0025dee5 in __libc_message (do_abort=2, fmt=0x321578 "*** glibc detected *** %s: %s: 0x%s ***\n")
at ../sysdeps/unix/sysv/linux/libc_fatal.c:189
#4 0x00267ff1 in malloc_printerr (action=<value optimized out>, str=0x6 <Address 0x6 out of bounds>, ptr=0x8055a60) at malloc.c:6217
#5 0x002696f2 in _int_free (av=<value optimized out>, p=<value optimized out>) at malloc.c:4750
#6 0x0026c7cd in *__GI___libc_free (mem=0x8055a60) at malloc.c:3716
#7 0x0025850a in _IO_new_fclose (fp=0x8055a60) at iofclose.c:88
#8 0x0804b9c0 in main () at ga.c:1100
The line number 1100, is the line where I am doing the fclose()in the above code segment. What is the reason for the above behavior? Any pointers is appreciated.
行号 1100 是我fclose()在上述代码段中执行的行。上述行为的原因是什么?任何指针表示赞赏。
(I am on Linux and using gcc)
(我在 Linux 上使用 gcc)
回答by Thomas Pornin
When you call fclose(), glibc releases some dynamically allocated structures; internally there is a free()call. malloc()and free()rely on rather complex, dynamically built structures. Apparently, glibc found that the structures were in an incoherent state, to the point that safe memory release cannot be done. glibc decided that the problem was serious enough to warrant an immediate abort.
当您调用 时fclose(),glibc 会释放一些动态分配的结构;内部有free()电话。malloc()并free()依赖于相当复杂的、动态构建的结构。显然,glibc 发现这些结构处于不连贯的状态,以至于无法进行安全的内存释放。glibc 认为问题严重到需要立即中止。
This means that you have a bug somewhere in your code, possibly quite far from the snippet you show, a buffer overflow or a similar out-of-place memory write which damages the memory allocation structures.
这意味着您的代码中某处存在错误,可能与您显示的代码段相距甚远,缓冲区溢出或类似的异地内存写入会损坏内存分配结构。
You may want to try Valgrindor Electric Fenceto sort such problems out.
您可能想尝试Valgrind或Electric Fence来解决此类问题。
回答by Simon Nickerson
I don't know if it's causing your particular problem, but you should always check the FILE *pointer returned by fopen()in case it's NULL.
我不知道它是否导致了您的特定问题,但是您应该始终检查FILE *返回的指针fopen(),以防它是NULL.

