Machine-translated by Google. Questions are authored in English.
Top

Discussion

Output?

#include <stdio.h>
#include <stdlib.h>
  
void fun(int *a)
{
    a = (int*)malloc(sizeof(int));
}
  
int main()
{
    int *p;
    fun(p);
    *p = 6;
    printf("%d\n",*p);
    return(0);
}

  • A.May not work
  • B.Works and prints 6

Answer: A

Correct answer: May not work

The pointer is passed by value, so fun receives a copy. Assigning the result of malloc to that copy changes nothing in main, where p is still uninitialised.

Writing *p = 6 then dereferences an indeterminate pointer, which is undefined behaviour - it may crash, may appear to work, may corrupt something else. To change the caller's pointer the function would need a int ** parameter, or it would have to return the new address.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.