更改main的签名时为什么会出现段错误? [英] Why am I getting segfault when changing the signature of main?
问题描述
我正在尝试着进入C语言,并编写了此程序,该程序在随机位置显示kb的RAM.这是代码,它可以正常工作:
I am trying to get my feet into C, and wrote this program that displays a kb of my RAM in a random location. Here is the code, and it works fine:
#include <stdio.h>
int main(){
char *mem;
for(int i =0; i < 1024; i++){
mem++;
printf("%c", *mem);
}
return 0;
}
此后,我对代码进行了以下更改,每次运行程序时都会遇到段错误:
After that, I did the following change in my code, and I get segfaults every time I run my program:
#include <stdio.h>
// Just added this signature
int main(int argc, char *argv[]){
char *mem;
for(int i =0; i < 1024; i++){
mem++;
printf("%c", *mem);
}
return 0;
}
我的蜘蛛感觉告诉我,我得到的段错误是随机的,也应该在第一个示例中引起,但是一次又一次地运行不同的程序使它看起来像是可预测的行为.
My spider senses tell me that the segfaults I get are random, and should also be caused in the first example, but running the different programs again and again makes it look like predictable behaviour.
$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
推荐答案
您的摘录都调用未定义的行为尝试
- 越界(
mem++;
,无分配) - 使用未初始化的值(访问
*mem
)
- Go out of bound (
mem++;
, with no allocation) - use uninitialized values (accessing
*mem
)
当前版本.
请记住,指针不会神奇地继承(或获取)内存,通常,您需要使指针指向有效的对象.
Remember, pointers do not magically inherit (or acquire) memory, you need to make a pointer point to something valid, in general.
这篇关于更改main的签名时为什么会出现段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!