0

this one is from a job interview.

#include <stdio.h>
#include <stdlib.h>

void func(int* x)
{
    x =(int*)malloc(sizeof(int));
    *x = 17;
}

void main() {
    int y = 42;
    func(&y);
    printf("%d", y);
}

The question is what will be printed and what's wrong here.

I saw one solution that claimed that x is a local variable so the 42 will be printed and the problem is the memory leak. But I don't think so, since I pass the address of y. It seems to me that the use of int as a pointer (where one is 4 bytes and the other is 8 bytes) is actually the problem. Can you give your opinion about it?

Thanks

Matan L.
  • 329
  • 2
  • 7
  • 3
    _I saw one solution that claimed that x is a local variable so the 42 will be printed and the problem is the memory leak._ That is correct. – Martin Liversage Mar 05 '17 at 09:48
  • Use a debugger, step through the code, observe changes of *all* variables (both local to the current function and those up the call stack) at every step. – n. m. could be an AI Mar 05 '17 at 09:49
  • There is no int value used as a pointer. The address of y is passed by value to `func`. The address of `y` is of type `int*` which is perfectly OK here. – Gerhardh Mar 05 '17 at 12:30
  • Also `void main()` is wrong here. ;) – Gerhardh Mar 05 '17 at 12:31
  • 1
    You pass the address of `y` and then throw that address away when you replace it with a `new` address. It is to that new address you make the assignment not the address of `y`. – Galik Mar 05 '17 at 13:29

0 Answers0