retagged by
571 views
3 votes
3 votes

Consider the following C code where main shows the intended use of the functions relating to struct foo.

struct foo {
    int x;
    int y;
    int * p;
};

struct foo* make_foo() {
    struct foo *foo = malloc(sizeof(struct foo ));
    foo->y = 2;
    foo->x = foo->y*2;
    foo->p = malloc(sizeof(int));
    *(foo->p) = 42;
    return foo;
}

void update_foo(struct foo *foo) {
    int num = *(foo->p);
    foo->p = malloc(sizeof(int));
    *(foo->p) = num + 1;
}

void free_foo(struct foo *foo) {
    free(foo);
    free(foo->p);
}

int main() {
    struct foo *f = make_foo();
    update_foo(f);
    free_foo(f);
}


Which of the following is true about the given program?

  1. Given program has a memory leak
  2. Given program has a dangling pointer
  3. Given program may result in run time error
  4. Given program will result in a compile-time error
retagged by

1 Answer

3 votes
3 votes
Option A: If we look at the function make_foo(), there is a pointer foo which points to memory created which is equivalent to size struct foo in the heap section. We are assigning integer value y as 2 and x as y*2 which is 4. foo->p is basically pointer to an integer which is present in the heap section. *(foo->p) is basically accessing the integer present in the heap section and it stores value 42.Adress of this struct foo created in the heap section is returned by this function. In update foo function there is a case of memory leak when fooo->p points to a new integer.

Option B:In free_foo(f)  we are freeing the whole thing pointed by free pointer. foo->p means (*foo).p which means we are accessing the memory pointed by foo which is already freed. Hence, it may not be accessible and would result in case of  a dangling pointer.

Option C: It may  result in a runtime error as the memory pointed after freeing foo as given in the above option may not be available to access by the operating system.

Option D:In the compilation stage, there is no error in the code / code format as all the functions are properly defined and there is no error in the code that is present.
Answer:

Related questions