【问题标题】:Dynamically allocated array changing contents unwantedly in C running on virtual machine在虚拟机上运行的 C 中动态分配的数组更改内容
【发布时间】: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 *arraysizeof array[0]可能会更好。
  • valgrind 和 AddressSanitizer 等工具会立即为您捕获此类错误。如果尚未安装,它们很容易在 Ubuntu 上安装;检查出来!

标签: c malloc virtualbox


【解决方案1】:

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; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2011-06-05
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2013-05-24
    相关资源
    最近更新 更多