1

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?

3
  • 3
    A typical beginner's error: malloc(26*sizeof(point*))-> malloc(26*sizeof(point)) Commented May 30, 2016 at 10:28
  • 2
    Or, vehicle = malloc(26*sizeof(*vehicle)); Commented May 30, 2016 at 10:29
  • Just a suggestion: type point *vehicle instead of point* vehicle because this is what declarations mean in C: base_type thing_that_gives_base_type ; This helps me to think clearly. Commented May 30, 2016 at 10:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah okay after reading some tutorials I must have confused arrays of structs and arrays of pointers to structs ^^ Thank you very much!
Or write self-documenting code: malloc( sizeof(point[26]) ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.