我在声明中有疑问
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);
}
Run Code Online (Sandbox Code Playgroud)
你的代码看起来不错,请注意sbrk(2)几乎已经过时(并且线程不友好),大多数malloc实现使用mmap(2)代替.
什么是未定义的行为是返回局部变量的地址,如
void* topofstack() {
char c;
return &c;
}
Run Code Online (Sandbox Code Playgroud)
最近的海湾合作委员会编制者(例如4.8)会发出警告,至少-Wall你应该使用它.关于调用堆栈,请参阅此答案,该答案提供了许多有用的链接.
在编写一些malloc代码时,也要对代码进行编码free(并尽量避免经常进行系统调用,因此free在malloc可能的情况下重新使用-d内存).另请参阅现有malloc自由软件实现的源代码.该MUSL libc中有一些相当可读的malloc / ...