这个int指针示例需要malloc吗?

use*_*521 2 c malloc int pointers scope

以下应用程序适用于已注释掉的malloced int和仅使用int指针指向本地int"a"时.我的问题是如果没有malloc这样做是否安全,因为当函数'doit'返回时,我认为int'a'超出范围,而int*p指向什么都没有.该程序是否由于其简单性而不是错误的或者这是完全正常的吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct ht {
    void *data;
} ht_t;

ht_t * the_t;

void doit(int v)
{
    int a = v;
    //int *p = (int *) malloc (sizeof(int));
    //*p = a;
    int *p = &a;

    the_t->data = (void *)p;
}

int main (int argc, char *argv[])
{
    the_t = (ht_t *) malloc (sizeof(ht_t));
    doit(8);
    printf("%d\n", *(int*)the_t->data);
    doit(4);
    printf("%d\n", *(int*)the_t->data);
}
Run Code Online (Sandbox Code Playgroud)

Ill*_*ian 5

是的,在函数不再在范围内后取消引用指向本地堆栈变量的指针是未定义的行为.你碰巧不幸的是,在你尝试再次访问它之前,内存没有被覆盖,被释放回操作系统或者变成了一个指向恶魔工厂的函数指针.

  • 你的意思是:"你只是不幸的是你在这种情况下的实现不会崩溃"? (4认同)
  • @Deduplicator是的,但我想给出一些他可能遇到的其他问题可能有用的例子. (2认同)