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
P.s. 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).
list->next = NULL; list = list->next;does not look very good to me