问题描述
当我尝试code以下正常工作。我缺少的东西吗?
when I try the code below it works fine. Am I missing something?
main()
{
int *p;
p=malloc(sizeof(int));
printf("size of p=%d\n",sizeof(p));
p[500]=999999;
printf("p[0]=%d",p[500]);
return 0;
}
我使用malloc(0 *的sizeof(int)的)或任何尝试过,但它工作得很好。当我不使用malloc在所有的程序只崩溃。所以,即使我分配内存0为阵P,它仍然正常存储值。那么,为什么我连使用malloc困扰呢?
I tried it with malloc(0*sizeof(int)) or anything but it works just fine. The program only crashes when I don't use malloc at all. So even if I allocate 0 memory for the array p, it still stores values properly. So why am I even bothering with malloc then?
推荐答案
这可能的显示的做工精细,但它也不是很安全的。通过编写的内存分配的内存块以外的数据要覆盖一些数据,你不应该。这是设计缺陷和其他内存错误的最大原因之一,什么你用它出现在这套短节目的工作观察是什么使得它如此难以追捕的根本原因。
It might appear to work fine, but it isn't very safe at all. By writing data outside the allocated block of memory you are overwriting some data you shouldn't. This is one of the greatest causes of segfaults and other memory errors, and what you're observing with it appearing to work in this short program is what makes it so difficult to hunt down the root cause.
文章,特别是对内存损坏的零件,开始理解这个问题。
Read this article, in particular the part on memory corruption, to begin understanding the problem.
是用于分析内存错误,如您提供的一个很好的工具。
Valgrind is an excellent tool for analysing memory errors such as the one you provide.
@大卫做了一个很好的注释。比较运行的结果运行。注意在运行时错误后的结果上ideone.com(含pretty多没有有用的输出!)(点击链接),而前者是成功的,你经历过。
@David made a good comment. Compare the results of running your code to running the following code. Note the latter results in a runtime error (with pretty much no useful output!) on ideone.com (click on links), whereas the former succeeds as you experienced.
main()
{
int *p;
p=malloc(sizeof(int));
printf("size of p=%d\n",sizeof(p));
p[500]=999999;
printf("p[0]=%d",p[500]);
p[500000]=42;
printf("p[0]=%d",p[500000]);
return 0;
}
这篇关于写的malloc后指针出界()不会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!