I am taking an OS course and I have some questions about the following codes
#include <stdio.h>
int * addition(int a, int b){
int c = a + b;
int *d = &c;
return d;
}
int main(void){
int result = *(addition(1,2));
int *result_ptr = addition(1,2);
/*never interchange */
printf("result = %d
", *result_ptr);
printf("result = %d
", result);
return 0;
}
//this code outputs 3
3
Here is what happens when i swap the printfs, in fact the second one just prints out a random address
#include <stdio.h>
int * addition(int a, int b){
int c = a + b;
int *d = &c;
return d;
}
int main(void){
int result = *(addition(1,2));
int *result_ptr = addition(1,2);
/*never interchange */
printf("result = %d
", result);
printf("result = %d
", *result_ptr);
return 0;
}
//this code outputs 3
and a random address
However, if i make them into one printf
#include <stdio.h>
int * addition(int a, int b){
int c = a + b;
int *d = &c;
return d;
}
int main(void){
int result = *(addition(1,2));
int *result_ptr = addition(1,2);
/*never interchange */
printf("result = %d %d
", result, *result_ptr);
return 0;
}
//this code outputs 3 3
I wonder if the printf clear the memory so the pointer becomes dangerous?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…