2014-02-26 56 views
1

运行INT一个奇怪的场景,比我要求的malloc被分配更多的内存:Ç - 的malloc分配太多内存

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,我得到:

enter image description here

所以首先,数组应为5个元素。但第二,为什么0到底?我为mallocing只有10/2 = 5整数的空间。

编辑:

打印代码:

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

嗯,我可能刚才已经回答这里我自己的问题,我猜它超出了secondArray印刷,显示0,而不是数组本身。

-

其实,问题是,我也没有这样做:

secondArray[numberOfElements] = '\0'; 

这就是为什么它被印超越。

+0

由于您不显示打印代码,我们只能猜测。一个合理的猜测是,你打印'for(int i = 0; i

+0

我将添加打印代码 – Live2Enjoy7

+1

我可能回答了我自己的问题 – Live2Enjoy7

回答

2

malloc实际上是正确地分配正确的金额。

但是,您正在访问分配以外的内存。

什么存在是完全未定义的,可能真的是任何东西。

就你而言,这是一个“垃圾”号和四个零。

0

你真幸运。 Malloc可以并且有时会从操作系统的更多内存中请求 - 考虑到分页。有时候甚至不需要询问操作系统的内存,因为它已经提前要求额外的内存。因此,malloc可以请求一页内存 - 更多的内容足以满足您的请求,并且额外的内存恰好被零填充。

你是在未定义的行为之地。所以所有投注都关闭。

0
its print 0 0 0 0 because in C no array bound if you define your array size is 4 but u 
want to store data more than array size you can store so you print your array 
for(i = 0; i < numberOfElements; i++) its give data and 0 also because you store the data 
only 5 position but you print it max size so it give you 0 0 0 

int *secondArray = malloc(sizeof(int) * numberOfElements/2); // no matter either use it or 
int *secondArray = malloc(sizeof(int)); 
// this will take same memory