我对这个说法有疑问
p = my_malloc(4);
my_malloc 有一个名为 p 的局部指针,当函数返回时指针的地址将被释放。那么 main 中的 int* p 是如何保存函数返回的地址的呢。当一个函数返回时,它使用的地址可能会也可能不会被其他函数或进程使用。那么下面的程序是未定义的行为吗?
#include<stdio.h>
#include<unistd.h>
void* my_malloc(size_t size){
void *p;
p = sbrk(0);
p = sbrk(size); // This will give the previous address
//p = sbrk(0); // This will give the current address
if(p != (void *)-1){
printf("\n address of p : 0x%x \n",(unsigned int)p);
}
else{
printf("\n Unable to allocate memory! \n");
return NULL;
}
return p;
}
int main(){
int* p;
p = my_malloc(4);
printf("\n address of p : 0x%x \n",(unsigned int)p);
}
最佳答案
你的代码看起来不错,注意 sbrk(2)几乎过时(并且线程不友好),大多数 malloc 实现使用 mmap(2)相反。
什么是未定义行为就是返回一个局部变量的地址,比如
void* topofstack() {
char c;
return &c;
}
和最近的 GCC 编译器(例如 4.8)将发出警告,至少对于您始终应该使用的 -Wall
是这样。关于调用堆栈,请参阅 this answer其中提供了很多有用的链接。
在编写一些 malloc
时,也要编写 free
(并尽量避免过于频繁地进行系统调用,因此重新使用 free
>-d 尽可能在 malloc
中存储)。另请查看现有 malloc 自由软件实现的源代码。
MUSL libc有一些相当可读的malloc/ ...
关于c - 正在返回一个本地指针导致未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16532983/