casting something from 1 byte to 8
Dec 14, 2017 at 10:26pm UTC
When i build and run this program i get no errors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <stdio.h>
#include <stdlib.h>
struct test
{
int mytest;
int myothertest;
};
struct memory
{
void * mymemory;
};
int main(void )
{
memory mem;
mem.mymemory = malloc(1);
test* testptr = (test*)mem.mymemory;
testptr->mytest = 3;
testptr->myothertest=4;
printf("mytest: %d\nmyothertest: %d\n" ,testptr->mytest,testptr->myothertest);
free(mem.mymemory);
return 0;
}
but since im only allocating 1 byte of memory and casting it to something that is 8 bytes
shouldn't it give me an override memory exception or something?
Last edited on Dec 14, 2017 at 10:30pm UTC
Dec 14, 2017 at 10:39pm UTC
You do write into (and read from) memory that you have not allocated. That is undefined behaviour.
Not crashing is equally undefined as a crash. A crash is much more merciful, for it hints about an issue.
Topic archived. No new replies allowed.