关于fprint和指针的一些问题 [英] Some issue concerning fprint and pointers

查看:180
本文介绍了关于fprint和指针的一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以一个操作系统课程,我有以下codeS的一些问题

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\n", *result_ptr);
    printf("result = %d\n", result);
    return 0;
}
//this code outputs 3
                    3

下面是当我交换printfs输出,其实第二个刚刚打印出一个随机地址会发生什么

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\n", result);
    printf("result = %d\n", *result_ptr);
    return 0;
}
//this code outputs 3
                    and a random address

但是,如果我让他们到一个printf的

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 \n", result, *result_ptr);
    return 0;
}
//this code outputs 3 3

我不知道的printf清除内存,以便指针变为危险?

I wonder if the printf clear the memory so the pointer becomes dangerous?

推荐答案

问题是在你的除了功能。你返回一个局部变量的地址。由于当地人住在栈中,该变量的存储超出范围时,该函数返回。这导致不确定的行为,如你经历了什么。

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.

有关这个正常工作,你需要使用在堆上分配内存的malloc

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.

这篇关于关于fprint和指针的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆