我正在尝试一些段错误示例,但没有一个导致错误。
源代码来自:http://www.unknownroad.com/rtfm/gdbtut/gdbsegfault.html
示例如下:
1 : #include <stdio.h>
2 : #include <stdlib.h>
3 : int main(int argc, char **argv)
4 : {
5 : char *buf;
6 :
7 : buf = malloc(1<<31);
8 :
9 : fgets(buf, 1024, stdin);
10: printf("%s\n", buf);
11:
12: return 1;
13: }
第一步是使用调试标志编译程序:
prompt> gcc -g segfault.c
现在我们运行程序:
prompt > ./a.out
Hello World!
Segmentation fault
prompt >
但是,上面的示例在我的Ubuntu中没有segfault运行。我认为它与gcc选项有关,但我无法找出导致这种情况的原因。当我在另一个发行版中运行时,会出现问题。
这是我的gcc:
的输出$ gcc -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5.1'
--with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs
--enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared
--enable-multiarch --enable-linker-build-id --with-system-zlib
--libexecdir=/usr/lib --without-included-gettext --enable-threads=posix
--with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls
--enable-clocale=gnu --enable-libstdcxx-debug --enable-plugin --enable-objc-gc
--enable-targets=all --disable-werror --with-arch-32=i486 --with-tune=generic
--enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu
--target=i486-linux-gnu
Thread model: posix
gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)
我的gcc也会自动初始化变量。我想禁用它。
有没有人遇到类似的问题,或对解决方案有任何想法?
答案 0 :(得分:2)
示例代码只有段错误,如果malloc(1<<31)
失败,则返回NULL。但是,如果您的系统能够分配2 GB内存而不会失败,malloc(1<<31)
会成功。该段错误示例代码段是系统通常无法分配该内存量的时间段。是否成功取决于物理内存量,其他进程占用的内存量,以及内核的内存过量使用策略,以及可能使用的(libc和)内核版本。因此,您看到的不同行为可能是overcommit sysctl的不同设置,运行的不同进程集,或者显然是不同的物理内存量的结果。
来自/usr/src/linux/Documentation/vm/overcommit-accounting
:
The Linux kernel supports the following overcommit handling modes
0 - Heuristic overcommit handling. Obvious overcommits of
address space are refused. Used for a typical system. It
ensures a seriously wild allocation fails while allowing
overcommit to reduce swap usage. root is allowed to
allocate slightly more memory in this mode. This is the
default.
1 - Always overcommit. Appropriate for some scientific
applications.
2 - Don't overcommit. The total address space commit
for the system is not permitted to exceed swap + a
configurable percentage (default is 50) of physical RAM.
Depending on the percentage you use, in most situations
this means a process will not be killed while accessing
pages but will receive errors on memory allocation as
appropriate.
The overcommit policy is set via the sysctl `vm.overcommit_memory'.
The overcommit percentage is set via `vm.overcommit_ratio'.