简体   繁体   English

数组指针永远不会出现段错误?

[英]Pointer of array never seg fault?

I have something I don't understand.我有一点不明白。

Here is what I do :这是我所做的:

float* test = (float*) malloc(4 * sizeof(float) );

And then I tried to do然后我试着做

test[100] = 1.0;
printf("%f\n",test[100]);

And ... It worked...而且......它起作用了......

I was waiting for a segmentation fault, but no and I don't understand why.我正在等待分段错误,但没有,我不明白为什么。 I wanted to do this to verify that my array has been correctly allocated.我想这样做是为了验证我的数组是否已正确分配。 I really didn't expected that, and maybe I miss something so I searched on the internet, and it seems that everybody get a segfault ... So I came here to ask.真没想到,可能是我漏了点什么,就上网搜了下,好像大家都有segfault……所以才过来问的。 Thanks谢谢

What you caused is undefined behavior - in this case, it works as expected, but it's a terrible idea to rely on it in any way: compiler optimizations or changing the operating system might suddenly cause "weird" behavior.您导致的是未定义的行为 - 在这种情况下,它按预期工作,但以任何方式依赖它都是一个糟糕的主意:编译器优化或更改操作系统可能会突然导致“奇怪”的行为。 You should read more on this topic, though in a nutshell, with undefined behavior, the compiler is allowed to do whatever it wants.您应该阅读有关此主题的更多信息,尽管简而言之,对于未定义的行为,编译器可以做任何它想做的事情。

I don't have enough knowledge to be sure, but I hypothesize that your Operating System prepared a whole memory page for your program.我没有足够的知识来确定,但我假设您的操作系统为您的程序准备了整个内存页面。 In Linux by default it is 4 KiB, and you accessed bytes up to 400, so there is still plenty of room.在 Linux 中,默认为 4 KiB,您访问的字节数高达 400,因此仍有足够的空间。 Thus, you might be accessing memory that is allocated for your program, as the operating system works with memory blocks not smaller than 4 KiB.因此,您可能正在访问为您的程序分配的内存,因为操作系统使用不小于 4 KiB 的内存块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM