Answer: A, C, D
Program 1:
int *p = malloc(sizeof(int));
*p = 0;
free(p);
*p = 0;
Line 1 is valid, so is line 2 where the value of that heap memory is altered, and line 3 where the memory is freed.
Writing into the freed memory is illegal: Dangling Pointer
Program 2:
int *p = malloc(sizeof(int));
*p = 0;
free(p);
p = 0;
It’s same as Program 1 till line 3. In line 4 however notice that the pointer is instructed to point to different memory location (0 in case of pointer is NULL)[1].
The value of pointer is changed not the value at memory location pointed by the pointer. This would be illegal if the reference to heap allocated memory was lost but since it was already freed this is legal.
Program 3:
int *p = malloc(3*sizeof(int));
*p = 0;
p++;
free(p);
Line 1, 2 are legal, and asks for 3 int memory locations. In line 3 the pointer is pointing to the second (1th) int and is then freed, but the the first (0th) int is never freed: Memory leak
Program 4:
int *p = malloc(sizeof(char));
*p = 0;
Asked for 1 byte (sizeof(char)) and using as int: Writing to an area which is not your own, illegal.
References:
- https://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0