I was messing around with the memset function and did this:
int* p = malloc(sizeof(int);
memset(p, 0, 10000);
I was wondering why this is valid. I've only allocated 5 bytes of memory yet I can take up 10000 with memset. Why should I even malloc the memory if I can take up more than allocated? Could someone explain?
It's undefined behaviour, as in you can do it but the results are not defined, as in unpredictable, as in the program might crash.
In this case you can only write to the allocated region, or sizeof(int) * 5
.
Why doesn't C prevent you from doing this? It's because the language design philosophy is that the programmer knows what they're doing and to not get in the way.