C中的Malloc和数组索引混乱 [英] Malloc and array index confusion in C

查看:72
本文介绍了C中的Malloc和数组索引混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图掌握C语言中的malloc函数,并编写了以下代码:

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个元素添加到数组中.为了测试是否正确,我添加了以下代码:

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]);

}

令人惊讶的是,该代码已完美编译并运行.那怎么可能?

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

推荐答案

C不执行 any 数组边界检查,因此,当您请求5个整数的空间时,您会使用更多空间.

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

实际上,您重写了确实没有为您的特定目的预留的4个内存位置.您的程序 past 过去为数组预留的内存区域,然后开始在分配的区域之外的内存中存储值.

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次工作,或者可能会在您下次尝试下一个时失败,并且很可能会出现"segmentation fault"消息.

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的返回值所做的一样,请注意负责边界检查,编译启用了高警告级别的代码,等等,这些是您最好的防御措施防止此类错误.其他工具(例如 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的最大优势之一,就是可以自由地做各种低级和高级的事情,这也是IMO最大的弱点之一.如果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 :)

这篇关于C中的Malloc和数组索引混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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