Program Unexpectedley crashes?

This is a small part of a program I'm working on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
long factorial (long a)
{
  if (a > 1)
   return (a * factorial(a-1));
  else
   return (1);
}

void generate_paths()
{
     int paths;
     paths = factorial(amm);
     int point[paths];
     srand (time(NULL));
     point[0]=1+ rand() % amm;
cout << point[0];
}


This is the part that is causing problems.

If the variable amm entered into the factorial function (line 12) is over 8 or so, the program crashes. But if it is under that then everything runs fine. Why is that??
Creating a stack array of 161,280 bytes is probably overflowing the stack.
Use this instead:
int *point=new int[paths];
ok thanks it worked...but i dont get why. where was i creating a stack of 161,280?
On line 13.
This kind of syntax
T array[N];
creates an array of sizeof(T)*N bytes in the stack. The stack is usually very limited, so creating too many or too large objects in it may overflow it, which is what happened here.

The syntax I gave you creates the array in the heap, which is much larger than the stack (many megabytes, or even gigabytes, larger). However, the memory is not freed when the function returns. This is both good and bad. It's good because that data can be accessed from anywhere at any time as long as the function has a pointer to it. It's bad because it means you have to free that memory yourself when you're done with it.
delete[] is used to free arrays, and delete is used to free single objects. Using delete[] on a single object will crash the program, and using delete on an array will only free the first element, leaving the others untouched. Both deletes call the destructors for the objects, if they have any.

http://www.cplusplus.com/doc/tutorial/dynamic.html
Topic archived. No new replies allowed.