在虚拟机上运行的C中,动态分配的数组在无意中更改内容



我有一个函数,在其中我动态分配一个数组,然后稍后使用它,但它在使用之间会任意变化:

void func(void){
//allocate two arrays. Tried both malloc and calloc
my_obj* array = calloc(arr_length, sizeof(my_obj*));
my_obj2* array2 = calloc(arr_length_2, sizeof(my_obj2*));
//now I fill the first array with some items
for(int i = 0; i < arr_length; i++){
my_obj o = {1, 2, 3, 4};
array[i] = o;
}
//now I test to make sure I filled the array as planned
for(int i = 0; i < arr_length; i++){
printf("%dn", array[i].x);
}
//everything prints as planned!
//now I fill the second array, without ever touching the first
for(int i = 0; i < arr_length_2; i++){
my_obj2 o = {1, 2};
array2[i] = o;
}
//now I print the first array again. Instead of the contexts I expect, 
//it is full of random data, seemingly completely unrelated to either its
//previous contents or the contents of the second array!
for(int i = 0; i < arr_length; i++){
printf("%dn", array[i].x);
}
}

正如代码注释中所提到的,我的数组似乎在神奇地改变,而我从未接触过它。是否有错误可能导致这种情况?值得注意的是,我在运行Ubuntu的VirtualBox虚拟机上运行代码。我没有收到任何错误信息。我已经三次检查过,我真的没有接触到两个打印例程之间的第一个数组。

sizeof(my_obj*)是指针大小的

my_obj* array = calloc(arr_length, sizeof(my_obj*));
my_obj2* array2 = calloc(arr_length_2, sizeof(my_obj2*));

在这里,您正在尝试访问尚未分配的内存:

...
array[i] = o; 

相关内容

  • 没有找到相关文章

最新更新