Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading