【发布时间】:2021-12-29 00:48:03
【问题描述】:
我有一个函数,我在其中动态分配一个数组,然后再使用它,但它在两次使用之间会任意变化:
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("%d\n", 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("%d\n", array[i].x);
}
}
正如代码的 cmets 中所提到的,我的数组似乎在发生神奇的变化,而我从未接触过它。是否存在可能导致此问题的错误?值得注意的是,我在运行 Ubuntu 的 VirtualBox VM 上运行我的代码。我没有收到任何类型的错误消息。我已经三重检查了我真的没有触及两个打印例程之间的第一个数组。
【问题讨论】:
-
my_obj* array = calloc(arr_length, sizeof(my_obj*));:为arr_length指针分配足够的空间,而不是my_obj对象的数量。你想要sizeof(my_obj),或者写sizeof *array或sizeof array[0]可能会更好。 -
valgrind 和 AddressSanitizer 等工具会立即为您捕获此类错误。如果尚未安装,它们很容易在 Ubuntu 上安装;检查出来!
标签: c malloc virtualbox