Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c - Some issue concerning fprint and pointers

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...