gpt4 book ai didi

C: malloc 和 free 的堆栈实现

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:53 26 4
gpt4 key购买 nike

我正在阅读 K&R 指针第 5.4 节,其中完成了 malloc()free() 的堆栈实现。我正在使用 gdb 调试代码,并且 alloc() 部分按预期工作。但是对于 afree() 部分,指针仍然指向与之前相同的位置。这是代码:

#include <stdio.h>
#define ALLOCSIZE 10000

static char allocbuf[ALLOCSIZE];
static char* allocp = allocbuf;

char* alloc(int n)
{
if(allocbuf + ALLOCSIZE - allocp >= n)
{
allocp += n;
return (allocp - n);
}
else
return 0;
}


void afree(char* p)
{
if(p >= allocbuf && p < allocbuf + ALLOCSIZE)
allocp = p;
}


int main()
{
char* a = alloc(10);
a = "ayushnair";
char*b = alloc(5);
b = "snea";
printf("%p %p\n", a, b);
afree(b);
afree(a);
printf("%p %p\n", a, b);
return 0;
}

新分配

allocp 0x601080

char* a = alloc(10); 之后

allocp 0x60108a

char* b = alloc(5); 之后

allocp 0x60108f

afree(b); 之后

allocp 0x60108f

afree(a); 之后

allocp 0x60108f

allocp 仍然指向 0x60108f。为什么不按代码更新?

最佳答案

在你的代码中,通过说

a = "ayushnair";

您没有将"ayushnair" 存储到 a 指向的内存中。 "ayushnair" 是一个字符串字面值,通过说

a = "ayushnair";

您正在将字符串文字的基地址存储到a 中。这样,您实际上是通过调用 alloc() 覆盖返回的指针。

这不是你想要的。您可能需要使用 strcpy()将字符串文字复制到 返回的指针中。

也就是说,根据当前代码,稍后通过调用

afree(b);
afree(a);

您正在调用 undefined behavior当您尝试比较不指向同一对象的指针时。

引用 C11,章节 §6.5.8,关系运算符

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

关于C: malloc 和 free 的堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com