c - 内存分配 : Why this C program works?

标签 c memory

<分区>

Possible Duplicate:
Returning the address of local or temporary variable

添加函数实现错误。它应该返回一个值而不是指针。 为什么在打印 ans 和 *ans_ptr 时没有任何错误,程序甚至给出了正确的结果?我猜 z 的变量已经超出范围,应该存在段错误。

#include <stdio.h>

int * add(int x, int y) {
    int z = x + y;
    int *ans_ptr = &z;
    return ans_ptr;
}

int main() {
    int ans = *(add(1, 2));
    int *ans_ptr = add(1, 2);

    printf("%d\n", *ans_ptr);
    printf("%d\n", ans);

    return 0;
}

最佳答案

它“有效”的原因是你运气好。返回指向局部变量的指针是未定义的行为!!你不应该这样做。

int * add(int x, int y) {
    int z = x + y; //z is a local variable in this stack frame
    int *ans_ptr = &z; // ans_ptr points to z
    return ans_ptr;
}


// at return of function, z is destroyed, so what does ans_ptr point to? No one knows.  UB results

关于c - 内存分配 : Why this C program works?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7321660/

相关文章:

android - 位图.recycle() - "IllegalArgumentException: Cannot draw recycled bitmaps"

c - c上的位解析程序

c - x86 32 位汇编中快速排序的优化

c - 简单的Make文件错误

android - SQLite Android 数据库光标窗口分配 2048 kb 失败

c++ - 指针内存分配和删除

node.js - 如何从 NodeJS 应用程序正确运行 bash 脚本?

c - ioctl 和 hgreg 获取硬盘信息

c++ - 加法和赋值错误

安卓内存泄漏