首页 > 解决方案 > malloc 复制中的分段错误

问题描述

我正在尝试实现The C programming language一书中的一个示例。该示例复制了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;
    }
}

标签: cpointerssegmentation-faultmalloc

解决方案


问题是

if (allocbuf + ALLOCSIZE - allocp <= n) /* is there enough space in the buffer? */

你的比较是错误的。应该available memory >= n只是您的检查if available memory <= n和返回0

下面的修改应该工作

if (((allocbuf + ALLOCSIZE) - allocp) >= n) /* is there enough space in the buffer? */

推荐阅读