int *x = malloc(1); Dynamically allocates 1 byte of memory on the heap. This is bad because an int is usually 4 bytes, it should be
int *x = malloc(sizeof(int));
free(x) deallocates the memory on the heap thus *x becomes a dangling pointer, but the code will still run since it is pointing to the programs heap (allocated memory). It is just undefined behavior since you have no guarantee what is being stored at that memory location.
5
u/usa_reddit 2d ago
There are multiple bugs:
int *x = malloc(1); Dynamically allocates 1 byte of memory on the heap. This is bad because an int is usually 4 bytes, it should be
free(x) deallocates the memory on the heap thus *x becomes a dangling pointer, but the code will still run since it is pointing to the programs heap (allocated memory). It is just undefined behavior since you have no guarantee what is being stored at that memory location.
This is why pointers in C can be dangerous.