Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is in your addition function. You're returning the address of a local variable. Because locals live on the stack, the memory for that variable goes out of scope when the function returns. This caused undefined behavior such as what you experienced.

For this to work properly, you need to allocate memory on the heap using malloc:

int *addition(int a, int b){
    int *d = malloc(sizeof(int));
    *d = a + b;
    return d;
}

When this function returns, you need to be sure to free the pointer that was returned after you're done with it. Otherwise, you'll have a memory leak.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...