动态分配的数组在虚拟机上的 C 运行 中意外更改内容
Dynamically allocated array changing contents unwantedly in C running on virtual machine
我有一个函数,我在其中动态分配一个数组然后稍后使用它,但它在使用之间任意变化:
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);
}
}
如代码注释中所述,似乎我的数组在我从未接触过它的情况下发生了神奇的变化。是否有可能导致此问题的错误?值得注意的是,我 运行 我的代码在 VirtualBox VM 运行 Ubuntu 上。我没有收到任何类型的错误消息。我已经三次检查我确实没有触及两个打印例程之间的第一个数组。
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;
我有一个函数,我在其中动态分配一个数组然后稍后使用它,但它在使用之间任意变化:
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);
}
}
如代码注释中所述,似乎我的数组在我从未接触过它的情况下发生了神奇的变化。是否有可能导致此问题的错误?值得注意的是,我 运行 我的代码在 VirtualBox VM 运行 Ubuntu 上。我没有收到任何类型的错误消息。我已经三次检查我确实没有触及两个打印例程之间的第一个数组。
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;