我试图涉足 C 语言,并编写了这个程序,在随机位置显示我的 RAM 的 kb。这是代码,并且运行良好:
#include <stdio.h>
int main(){
char *mem;
for(int i =0; i < 1024; i++){
mem++;
printf("%c", *mem);
}
return 0;
}
之后,我对代码进行了以下更改,每次运行程序时都会出现段错误:
#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;
}
我的蜘蛛感觉告诉我,我得到的段错误是随机的,也应该是在第一个示例中引起的,但是一次又一次地运行不同的程序使它看起来像是可预测的行为。
$ 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
)
与当前版本。
请记住,指针不会神奇地继承(或获取)内存,一般来说,您需要使指针指向有效的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)