簡體   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