C-malloc分配过多的内存 [英] C - malloc allocating too much memory

查看:107
本文介绍了C-malloc分配过多的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个奇怪的场景中运行,其中malloc分配的内存超出了我的要求:

running int a strange scenario where malloc is allocating more memory than I ask for:

void function (int array [], int numberOfElements) {

int *secondArray = malloc(sizeof(int) * numberOfElements/2);

for (int i = 0; i < numberOfElements / 2; i++) {
    secondArray[i] = array[i];
  }
} 

比方说,数组是大约10个数字.当我在上面的代码之后打印出secondArray时,我得到:

Let's say array is a some 10 numbers. When I print out secondArray after the above code, I get:

因此,首先,数组应为5个元素.但是第二,为什么0到底呢?我只为10/2 = 5整数分配空间.

so first of all, the array should be 5 elements. But second, why the 0's in the end? I'm mallocing only space for 10/2 = 5 ints.

打印代码:

for (int d = 0; d < numberOfElements; d++) {
   printf("%i ", secondArray[d]);
}

嗯,我可能刚刚在这里回答了我自己的问题,我猜想是secondArray之外的打印显示0,而不是数组本身.

hmm I might have just answered my own question here, I'm guessing it's the printing beyond secondArray that shows 0, not the array itself.

-

实际上,问题在于我也没有这样做:

Actually, the problem is that I was also not doing this:

secondArray[numberOfElements] = '\0';

这就是为什么它超出打印范围的原因.

That is why it was printing beyond.

推荐答案

malloc实际上实际上分配了正确的数量.

malloc is actually allocating exactly the right amount.

但是,您正在访问的内存超出了分配范围.

However, you're accessing memory beyond the allocation.

存在的东西是完全未定义的,真的可以是任何东西.

What exists there is completely undefined and could really be anything.

在您的情况下,它是一个垃圾"数字和四个零.

In your case, it was one "junk" number and four zeroes.

这篇关于C-malloc分配过多的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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