Ç - malloc和阵列混乱 [英] C - malloc and arrays confusion

查看:148
本文介绍了Ç - malloc和阵列混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图把握在C malloc函数,和我写了下面code:

I was trying to grasp the malloc function in C, and I wrote the following code:

int i;

int *arr = (int*)malloc(5*sizeof(int)); 

if(arr==NULL){

  printf("Failed to allocate memory for arr...\n");
  exit(1);

}

我认为这意味着只有5个元素可以被添加到阵列。为了测试,如果这是真的,我增加了以下code:

I thought this meant that only 5 elements could be added to the array. To test out if that was true, I added the following code:

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
arr[5] = 6;
arr[6] = 7;
arr[7] = 8;
arr[8] = 9;

for(i=0;i<9;i++){

    printf("%d\n",arr[i]);

}

令人惊讶的是code编译并运行完美。这怎么可能?

Surprisingly, that code compiled and ran perfectly. How was that possible?

推荐答案

C不执行的任何的数组边界检查,所以当你要求的空间5的整数,你用得较多。

C doesn't enforce any array bounds checking, so while you requested space for 5 integers, you used more.

在事实上,你改写真的没有预留特定的目的,4个内存位置。你的程序去的过去的区域内存中被搁置的阵列,并开始存储在内存中分配的区域以外的值。

In fact you overwrote 4 memory locations that really weren't set aside for your specific purpose. Your program went past the area in memory that was set aside for your array, and started to store values in memory outside the allocated region.

,这个工作其实只是纯粹的运气,不是依赖于。它可以工作在未来100倍,也可能失败的下次的时候,你试试吧,用最有可能是分段错误消息。

The fact that this "worked" is just pure luck and not something to be dependent on. It may work the next 100 times, or it may fail the next time you try it, with most likely a "segmentation fault" message.

防御性编程,像你这样通过合理检查的malloc的返回值,被铭记的的负责边界检查,编译code具有较高的警告级别启用等都是一些最好的防御,以防止这些排序错误。其他工具,如的valgrind ,皮棉型跳棋也可以帮助,但最终它给你。

Defensive programming, like you did by sensibly checking the return value of malloc, being mindful that you are responsible for bounds checking, compiling code with high warning levels enabled, etc are some of your best defenses to guard against these sort of errors. Other tools, such as valgrind, lint type checkers can also help, but at the end it's up to you.

一架C最大的优势之一,它的自由,做各种各样的事情,低和高层次的,也是国际海事组织其最大的弱点之一。如果Java是沃尔沃,C或许更像是一个法拉利参差不齐休息,时间:)

One of C's greatest strengths, its freedom to do all sorts of things, low and high-level, is also one of its greatest weaknesses IMO. If Java is a Volvo, C is perhaps more like a Ferrari with spotty breaks at times :)

这篇关于Ç - malloc和阵列混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆