Pali
Pali

Reputation: 1357

Initializing array of structs strange behavior

I am using an array of structs and then set up the elements like the following:

#include <stdio.h>
#include <stdlib.h>

typedef struct _point {
    char s;
    unsigned int x;
    unsigned int y;
} point;

point* vehicle;

int main(int argc, char *argv[]) {
    /* 26 Vehicles */
    vehicle = malloc(26*sizeof(point*));
    for (int i = 0; i < 26; i++) {
        vehicle[i].s = ' ';
    }

    /* Print already existing vehicles */
    for (int i = 0; i < 26; i++) {
        if (vehicle[i].s != ' ') {
            printf("%c: x=%d y=%d\n", vehicle[i].s, vehicle[i].x, vehicle[i].y);
        }
    }

    return 0;
}

NOTE: this is not the actual code (which is too big to post) but the set up of the array and structs is the same.

As you can see, I set every vehicle[i].s to the space character, but the loop prints the following (not it this example code but in my actual code):

: x=32215344 y=0
P: x=0 y=33
: x=2105376 y=0

Question: how can it be that after the first loop, some elements are modified in the "background" without assigning them in the code? Or can some other malloc operations overwrite/reallocate the memory?

Upvotes: 1

Views: 57

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

The problem, as I see it is in

 vehicle = malloc(26*sizeof(point*));

you're allocating memory for the pointer-to-the-data-type type, whereas you should be allocating for the data type itself.

To elaborate, you want to allocate memory for 26 elements of type point (i.e., struct _point), not 26 point *.

Change

vehicle = malloc(26*sizeof(point));

or, for better,

vehicle = malloc(26*sizeof * vehicle);

Otherwise, you're running short of allocated memory when you try to dererference the pointer to access ns of instances. So, you end up accessing out-of-bound memory which causes undefined behavior.

That said, just an advice, if you know the size to be allocated beforehand, (26, for example), don't use dynamic memory, there's no need for it. Use an array.

Upvotes: 3

Related Questions