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;
}
Edit to address your numbered questions.
There are no data types you must allocate with malloc. Only if you want a pointer type to point to valid memory must you use the unary
&(address-of) operator ormalloc()or some related function.There is nothing wrong with your code – the line:
Allocates a structure on the stack – then everything works as normal. Structures are no different in this sense than any other variable. It’s not better or worse to use automatic variables (stack allocation) or globals or
malloc(), they’re all different, with different semantics and different reasons to choose them.In your example in #3,
foo2.b‘s value is undefined. Any automatic variable has an undefined and indeterminate value until you explicitly initialize it.