I have defined a basic list structure, and a simple insert
function, and a search
function. The code is below:
////////////////////////////////////////////////
typedef struct list
{
int item;
struct list *next;
}List;
////////////////////////////////////////////////
List * search_list(List * l, int i)
{
if(NULL == l)
return(NULL);
if(i == l->item)
return l;
else
return search_list(l->next, i);
}
////////////////////////////////////////////////
void insert_list(List ** l, int i)
{
List * p = new List();
p->item = i;
p->next = *l;
*l = p;
}
My main loop to test it, looks like this:
int main(int, char* argv[])
{
List * mylist = new List();
for(int i = 0; i < 8000; i++)
{
insert_list(&mylist,i);
}
int val = 2000;
List * s = search_list(mylist, val);
return 0;
}
When val
is 4000, the program completes ok. But when val
is 2000, i.e. 2000 indexes further down the list, Visual Studio terminates with a stack overflow.
Is the number of recursive calls in search_list()
causing a stack overflow? How can I get rid of this error?