Unknown Malloc stack overflow c

I have written a piece of code that takes several integers (as many as 100 000 int) as input from a file and stores them in a "recursive" struct.

As long as I run this code on my PC everything is fine.

Here is the code:

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);
    }
}

However, when I try to run this code on my Android phone, I get a

malloc stack overflow error

(I know that the stack space reserved on a phone is less then the one on a PC).

The problem is that, to my knowledge, this program should use a lot of stack memory.

This is what I think is happening inside my program (please correct me if I am wrong):

1). node* list = NULL ==> Space for a pointer (8 byte) is allocated on the stack;

2). list = insert(list, temp) ==> Goes to the end of data stream.

3). list = create() ==> The create() function is called;

4). node* list = (node*)malloc(sizeof(node)) ==> Space for a pointer is allocated on the stack (8 byte) and space for the struct is allocated on the heap (16 byte);

5). return list ==> create() function is closed, therefore the variable node* list on the stack is "freed" while the space allocated on the heap remains.

So my program should be using a lot of heap memory, but just 8 byte of stack memory (the ones needed for the first pointer in main ==> node* list = NULL ), how is it possible that I get error:

malloc stack overflow

?

Thank you

Lorenzo

Ps Sorry guys but I was trying to make my code shorter, but what I had written was no sense. I fixed it now (or I hope so).


You are overusing the variable list.

You need to retain a pointer your current node instead of overwriting it with the line:

list = create();

consider the following or similar:

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;
    }
}

I encourage you to wrap some of this logic in a function separate from main().

The actual cause of the segmentation fault is not in the code you showed, but in your current code when every you try to use list it is NULL, which is probably your undefined behavior.

链接地址: http://www.djcxy.com/p/80450.html

上一篇: 什么是StackOverflowError?

下一篇: 未知的Malloc堆栈溢出c