in Programming edited by
212 views
6 votes
6 votes

Mark all options which are likely to create problems with memory, i.e., run time error or has a memory leak.

Assume that malloc is successful in all cases.

Program 1:
int *p = malloc(sizeof(int));
*p = 0;
free(p);
*p = 0;
Program2:
int *p = malloc(sizeof(int));
*p = 0;
free(p);
p = 0;
Program 3:
int *p = malloc(3*sizeof(int));
*p = 0;
p++;
free(p);
Program 4:
int *p = malloc(sizeof(char));
*p = 0;
  1. Program $1$
  2. Program $2$
  3. Program $3$
  4. Program $4$
in Programming edited by
212 views

1 Answer

7 votes
7 votes

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:

  1. https://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0

2 Comments

In program 3, does free(p) will free 3 consecutive memory of integer memory size (starting from the second int) or it will just free only 1 integer size memory as it’s a integer pointer? Thus, creating memory leak of two integer sizes.
0
0

The free() is implementation dependent as per https://stackoverflow.com/a/7706451.

Ideally it should release the entire three bytes, but, you can see that you asked for four bytes and now are pointing to one byte ahead so three bytes must be released, but again we don’t know and neither do we need to.

This is what I found on https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf (the link may cause anxiety and acute depression, careful.)

0
0
Answer:

Related questions