繁体   English   中英

malloc复制中的分段错误

[英]Segmentation fault in malloc replication

我正在尝试实现The 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;
    }
}

问题是

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? */

你的问题在alloc(50); 至多为您提供 50字节的内存,而不是 50 int空间。 您需要使用alloc(50*sizeof(int)); .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM