【问题标题】:Segmentation fault in malloc replicationmalloc 复制中的分段错误
【发布时间】: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


    【解决方案1】:

    问题是

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

    你的比较是错误的。 它应该是available memory &gt;= n,但您检查if available memory &lt;= n 并返回0;

    下面的修改应该可以工作

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

    【讨论】:

    • 你是对的,比较是错误的。我改变了它,但仍然得到段错误。我在 main 中使用 alloc 函数的方式是否正确?
    • @JAV 是的,我可以毫无问题地运行您的程序。
    • @JAV 出了什么问题?
    • 哦,好吧,我的编译宏没有删除旧的二进制文件。现在一切正常。非常感谢:)
    【解决方案2】:

    您的问题出在alloc(50);,它为您提供了 50 个字节的内存,而不是 50 个int 的空间。您需要使用alloc(50*sizeof(int));。

    【讨论】:

    • 我试图改变它,但仍然有段错误。但是我的 alloc 使用定义为保存整数的缓冲区数组。那么这还不够吗?通过将 int 的 size 乘以 50,内存的整数框比需要的要多得多。还是我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2015-01-29
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多