【发布时间】:2019-02-01 07:24:21
【问题描述】:
我正在尝试实现C 编程语言一书中的一个示例。该示例复制了 malloc 的简化版本。我的实现产生了分段错误。函数 alloc 和 afree 基本上都是从书中抄来的。我正在尝试在 main.js 中使用这些功能。据我了解,只要两个地址都在同一个数组中,*(pointer+i) 表达式就会给我存储在指针旁边的地址中的值。它应该是隐含的满足,但显然,这还不够。
我怎样才能真正使用函数alloc和afree来创建动态数组?
#include <stdio.h>
int *alloc(int);
void afree(int *);
/* RETURNS SEGMENTATION FAULT, WHY? */
int main()
{
int *dyna_arr;
dyna_arr = alloc(50);
/* fill the array with integers */
for (int i = 0; i < 50; i++)
{
*(dyna_arr+i) = i;
}
for (int i=49; i>=0;i--)
{
printf(" %d", *(dyna_arr+i));
}
afree(dyna_arr);
}
#define ALLOCSIZE 10000
static int allocbuf[ALLOCSIZE];
static int *allocp =allocbuf; /* next free position in buffer */
/* alloc: return pointer to n ints */
int *alloc(int n)
{
if (allocbuf + ALLOCSIZE - allocp >= n) /* is there enough space in the buffer? */
{
allocp += n;
return allocp - n;
}
else /* not enough space */
{
return 0;
}
}
/* afree: free the storage pointed to by p */
/* Only possible in LIFO fashion */
void afree(int *p)
{
if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
{
allocp = p;
}
}
【问题讨论】:
标签: c pointers segmentation-fault malloc