1)
For which datatypes must I allocate memory with malloc?
- For types like structs, pointers, except basic datatypes, like int
- For all types?
2)
Why can I run this code? Why does it not crash? I assumed that I need to allocate memory for the struct first.
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint32; typedef struct { int a; uint32* b; } foo; int main(int argc, char* argv[]) { foo foo2; foo2.a = 3; foo2.b = (uint32*)malloc(sizeof(uint32)); *foo2.b = 123; } Wouldn't it be better to use
foo* foo2 = malloc(sizeof(foo)); 3) How is foo.b set? Does is reference random memory or NULL?
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint32; typedef struct { int a; uint32* b; } foo; int main(int argc, char* argv[]) { foo foo2; foo2.a = 3; }