C malloc struct throws memory violation exception (barebones example)

Viewed 139

Here is the example:

#include <stdio.h>

struct nums {
    int x;
    int y;
};

int main() {
    struct nums *ball = malloc(sizeof *ball * 4);
    ball[0].x = 2;
    printf("%d", ball[0].x);
    free(ball);
};

Error Details:

Exception thrown: write access violation.
**ball** was 0x6E919550.

I am very new to C and I would really appreciate someone to explain what specifically I am telling the computer to do here, why it is incorrect and also show me the correct way of doing this. Thanks.

EDIT: This seems to be functional code but does not run when I compile and run it in VS16 why could this be?

1 Answers

The most likely problem is a missing declaration for malloc(). You should add the line

#include <stdlib.h>

at the top of your code.

Without this line, the compiler may assume that malloc returns int. But if you're on a 64-bit platform, with 32-bit ints but 64-bit pointers, this will fail pretty badly. Your pointer variable ball is likely to end up holding just 32 of the 64 bits which malloc tried to return, with the other 32 scraped off. ball will therefore be an invalid pointer, leading to the exception you saw.

Did you get any warnings? My compiler complains

warning: implicitly declaring library function 'malloc'
note: include the header <stdlib.h>

Or, you might have gotten a message like

warning: implicit declaration of function 'malloc' is invalid in C99

If you got warnings like these, please don't ignore them, and do learn what they mean: they're definitely things you care about. And if you didn't get warnings like these, you should figure out how to enable them in your compiler. (Or if that's not possible, you should strongly consider switching to a better compiler, if at all possible.) Modern C programming practice definitely considers this error to be one worth warning about. And there are lots of mistakes like this that are easy to make, that are frustrating to debug, and that a good compiler will warn you about, at least if you let it.

Related