未知的 Malloc 堆栈溢出 c

Unknown Malloc stack overflow c

我写了一段代码,它从文件中输入几个整数(多达 100 000 int)并将它们存储在 "recursive" 结构中。

只要我 运行 这段代码在我的电脑上就一切正常。

代码如下:

typedef struct node{
    int data;
    struct node* next;
} node;

...

node* create(void){
    node* list = (node*)malloc(sizeof(node));
    return list;
}

node* insert(node* list, int temp){
    if(list == NULL){
        list = create();
        list->data = temp;
        list->next = NULL;
        return list;
    }
    list->next = insert(list->next, temp);
    return list;
}

int main(void){
    ...
    node* list = NULL;
    while(there is still data to input){
        list = insert(list, data);
    }
}

但是,当我尝试在我的 Android phone 上 运行 此代码时,我得到

malloc stack overflow error

(我知道 phone 上保留的堆栈 space 少于 PC 上的堆栈。

问题是,据我所知,这个程序应该使用大量堆栈内存。

这是我认为在我的程序中发生的事情(如果我错了请纠正我):

1). node* list = NULL ==> Space 为指针(8 字节)分配在堆栈上;

2). list = insert(list, temp) ==> 转到数据流的末尾。

3). list = create() ==>调用了create()函数;

4). node* list = (node*)malloc(sizeof(node)) ==> Space 指针分配在栈上(8 字节),space 结构分配在堆上(16 字节);

5). return list ==> create() 函数关闭,因此堆栈上的变量 node* list 是 "freed" 而分配在堆上的 space 仍然存在。

所以我的程序应该使用大量的堆内存,但只有 8 字节的堆栈内存(main ==> node* list = NULL 中第一个指针所需的),我怎么可能得到错误:

malloc stack overflow

?

谢谢

洛伦佐

P.s。对不起大家,但我试图让我的代码更短,但我写的是没有意义的。我现在修好了(或者我希望如此)。

您过度使用了变量列表。

您需要保留当前节点的指针,而不是用以下行覆盖它:

list = create();

考虑以下或类似的:

int main(void){
    ...
    node* list = NULL;
    node* current = NULL;
    node* next = NULL;
    while(...){
        ...
        next = create();
        if(list == NULL)   //list empty case
        {
            list = next;
            current = next;
        }
        current->next = next;
        next->next = NULL;
        current = next;
    }
}

我鼓励您将其中的一些逻辑包装在与 main() 分开的函数中。

分段错误的实际原因不在您显示的代码中,而是在您当前的代码中,当您每次尝试使用列表时它都是 NULL,这可能是您未定义的行为。