-1

I want to know how I am getting answer for the below code can anyone pls explain ..

In c language..

#include <stdio.h>

int*p;
void fun(int a, int b)
{
    int c;
    c = a+b ;
    p=&c;
}
int main()
{
    fun(2,3);
    printf("%d",*p);
    return 0;
}

If the pointer is declared globally how it's possible to access the memory that was collapsed after return to the main function

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
  • 3
    It's Undefined Behaviour to attempt to access a local variable after the function has exited. UB means it can appear to "work", can crash, can produce wrong results or any other unpredictable behaviour. Such code is always incorrect (even if the result appears correct) and can fail at any time. – kaylum May 21 '22 at 05:59
  • @kaylum Why don't you consider that worth an answer? – Yunnosch May 21 '22 at 07:01
  • RamaKrishna What do you mean by "how I am getting answer for the below code"? What is "answer" in a context without question? Do you mean how the value makes it into the output? Do you mean that you want an answer to the question beneath the shown code? Or are those two separate questions? What makes you wonder? You are right to wonder, see comment by kaylum, but maybe explain what is puzzling you. Maybe your understanding of the (unusual) word "collapse" could help if you explain it. – Yunnosch May 21 '22 at 07:05
  • You have a pointer that points to memory that "isn't there any more", and you're surprised that, magically, the memory that "isn't there" might still be accessible — and might even contain the "correct" value. There's an excellent old analogy about this phenomenon — one of the best answers on SO, ever — [here](https://stackoverflow.com/questions/6441218). – Steve Summit May 21 '22 at 07:10
  • 1
    By the way, this situation has nothing to do with whether the pointer is global or not. There's no problem whatsoever with having a global pointer that points to (valid) local data. On the other hand, when it comes to invalid data, an invalid pointer value is just as invalid whether it's stored in a pointer variable of global, local, or other scope. – Steve Summit May 21 '22 at 07:16
  • What did you expect to happen instead? – n. m. could be an AI May 21 '22 at 07:34

1 Answers1

1

You don't have the local variable c after the expiration of the function. So the pointer p is pointing to what? Your code has unpredictable behavior. The solution is allocating some memory and assigning it to p. note that it is a best practice to free the allocated memory at the end of using p.

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

int* p;

void fun(int a, int b) {
    int* c = malloc(sizeof(int));
    *c = a + b;
    p = c;
}

int main() {
    fun(2, 3);
    printf("%d", *p);
    free(p);
    return 0;
}
alitayyeb
  • 77
  • 7