【发布时间】:2019-09-01 07:24:45
【问题描述】:
在 c 中,
当定义像int a; int* b; 这样的变量时,内存是在堆栈中分配的。
使用 malloc 时,使用堆内存。
我的问题是,如果在如下函数中:
void* function () {
int counter = 0;
while() {
... does some counting
counter++;
}
return (void *) counter;
}
它返回一个指向计数器的指针,计数器的内存在哪里?代码段?
【问题讨论】:
-
它没有返回指向
counter的指针。它将counter的值转换为void *。这将是一个无效的指针,因为它的任何使用都会产生未定义的行为。所以它不必“生活”在内存中的任何地方。
标签: c memory-management