Could you please help me check where is the bug
/*main.c*/
#include <stdio.h>
long *new_42(void); // creates a new long in dynamic memory
(stack)
void donotmuchofanything(long *);
void main () {
long *long_ptr;
long_ptr = new_42();
printf("The current value is %ld.\n", *long_ptr);
donotmuchofanything(long_ptr);
printf("The current value is %ld.\n", *long_ptr);
}
/*dynamic.c*/
long *new_42(void) {
long x;
long *ret;
x = 42;
ret = &x;
return ret;
} // new_42
long N = 10;
void donotmuchofanything(long *a) {
if (N--) {
donotmuchofanything(a);
N++;
}
} // donotmuchofanything
When you compare the output with the corresponding C code, it appears that there is a bug in printf(). Perhaps in the other function. There is a bug, however it is not within either function. Explain where the bug really is, and why printf() displays what it does
If you have any doubts then please comment below.
Please upvote.
Solution is simple, just use static long x variable instead of long x.
(OR)
Just use declare long x as global variable instead of using local variable.
But why?
Static variables maintain the value of the variable unchanged
after out of their scope.
They maintains previous scope so need not to initialize again in
new scope.
But that's not the case with local variables.
In your code,local variable x is storing a garbage value.
(OR)
Scope of global variables is out of all functions.
So value you refer or update the variable wherever and whenever is
not necessary.
Solution 1
#include <stdio.h>
long *new_42(void); // creates a new long in dynamic memory
(stack)
void donotmuchofanything(long *);
void main () {
long *long_ptr;
long_ptr = new_42();
printf("The current value is %ld.\n", *long_ptr);
donotmuchofanything(long_ptr);
printf("The current value is %ld.\n", *long_ptr);
}
/*dynamic.c*/
long *new_42(void) {
static long x;//Bug is fixed
long *ret;
x = 42;
ret = &x;
return ret;
} // new_42
long N = 10;
void donotmuchofanything(long *a) {
if (N--) {
donotmuchofanything(a);
N++;
}
}
Solution 2:
#include <stdio.h>
long *new_42(void); // creates a new long in dynamic memory
(stack)
void donotmuchofanything(long *);
long x;//Bug is fixed
void main () {
long *long_ptr;
long_ptr = new_42();
printf("The current value is %ld.\n", *long_ptr);
donotmuchofanything(long_ptr);
printf("The current value is %ld.\n", *long_ptr);
}
/*dynamic.c*/
long *new_42(void) {
long *ret;
x = 42;
ret = &x;
return ret;
} // new_42
long N = 10;
void donotmuchofanything(long *a) {
if (N--) {
donotmuchofanything(a);
N++;
}
}

Could you please help me check where is the bug /*main.c*/ #include <stdio.h> long *new_42(void); //...