为什么下面的代码没有任何崩溃@ runtime?
而且尺寸完全取决于机器/平台/编译器!! 我甚至可以在64位机器上放弃200.如何在OS中检测到主函数中的分段错误?
int main(int argc, char* argv[])
{
int arr[3];
arr[4] = 99;
}
Run Code Online (Sandbox Code Playgroud)
这个缓冲空间来自哪里?这是分配给进程的堆栈吗?
这是我的最小可重现示例:
#include <stdio.h>
int main( int argc, char* argv[])
{
printf (" this is the contents of argc:%d\n",argc);
int i;
for (i = 0; i < argc ; i++){
printf(" argv = %d = %s\n",i,argv[i]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我argc将 for 循环更改为数字时,比方说10,代码在到达之前崩溃10:
$ ./argc one two three
this is the contents of argc:4
argv = 0 = ./argc
argv = 1 = one
argv = 2 = two
argv = 3 = three
argv …Run Code Online (Sandbox Code Playgroud) 我期望以下代码段使用来为五个成员分配内存calloc。
$ cat calloc.c
// C program to demonstrate the use of calloc()
// and malloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
arr = (int *)calloc(5, sizeof(int));
printf("%x\n", *arr);
printf("%x\n", *(arr+1));
printf("%x\n", *(arr+2));
printf("%x\n", *(arr+3));
printf("%x\n", *(arr+4));
printf("%x\n", *(arr+5));
printf("%x\n", *(arr+6));
// Deallocates memory previously allocated by calloc() function
free(arr);
return(0);
}
Run Code Online (Sandbox Code Playgroud)
但是它似乎分配了五个以上的空间。它分配了六个成员,为什么呢?
./a.out
0
0
0
0
0
0
411
Run Code Online (Sandbox Code Playgroud) 假设我有以下数组
unsigned char array[5];
Run Code Online (Sandbox Code Playgroud)
所以我试图了解访问中到底什么是未定义的
array[6]
Run Code Online (Sandbox Code Playgroud)
据我了解,编译器将尝试读取内部的值*(array+6),因此它被定义。所以,如果我理解正确的话,未定义的是当你尝试读取未初始化的内存时会发生什么。
如果是这种情况,那么这里的最佳答案说,除非有陷阱表示,否则定义了读取未初始化的值,但我们知道 unsigned char 没有这种表示。
那么这里定义得好吗?它总是会读到吗*(array+6)?