为什么在更改main的签名时会出现段错误?

Lou*_*pax 3 c pointers pointer-arithmetic

我试图让我的脚进入C,并编写了这个程序,在随机位置显示我的RAM的kb.这是代码,它工作正常:

#include <stdio.h>

int main(){
    char *mem;
    for(int i =0; i < 1024; i++){
        mem++;
        printf("%c", *mem);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

之后,我在代码中进行了以下更改,每次运行程序时都会出现段错误:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的蜘蛛感官告诉我,我得到的段错是随机的,也应该在第一个例子中引起,但是一次又一次地运行不同的程序使它看起来像可预测的行为.

$ 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
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 6

在您尝试时,两个片段都会调用未定义的行为

  1. 走出界限(mem++;没有分配)
  2. 使用未初始化的值(访问*mem)

与当前版本.

请记住,指针不会神奇地继承(或获取)内存,通常需要使指针指向有效的内容.