Home > Blockchain >  Dynamically allocated array changing contents unwantedly in C running on virtual machine
Dynamically allocated array changing contents unwantedly in C running on virtual machine

Time:11-18

I have a function in which I dynamically allocate an array and then use it later, but it changes arbitrarily in between uses:

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);
    }
}

As mentioned in the comments of the code, it seems like my array is magically changing without me ever touching it. Is there a bug which could cause this? It's worth noting that I am running my code on a VirtualBox VM running Ubuntu. I don't receive any kind of error message. I have triple checked that I really am not touching the first array in between the two print routines.

CodePudding user response:

sizeof(my_obj*) is pointer size

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

Here your'e trying to access memory that you havent allocated:

...
array[i] = o; 
  • Related