Dragons_Lair5
Dragons_Lair5

Reputation: 745

Segmentation fault(core dumped) variable assignment

I have a program written in C++, compiled with G++, running in Ubuntu 13.04 32 bits, that is giving the following error: "Segmentation fault (core dumped)".

int main(int argc, char *argv[]){
printf("1\n");
int x = 0 , y = 0, count = 0;
printf("2\n");
char c;
printf("3\n");
int n_frames = (atoi(argv[1]) - 1);
printf("4\n");
int windowSize = WINDOW_SIZE; // WINDOW_SIZE is a define
printf("5\n");
// And the program go on....

long double frames[n_frames][377];

long double dis_frames[n_frames - (windowSize - 1)];
int tam_dis_frames = n_frames - (windowSize - 1);
long double white_top_hat[tam_dis_frames];

When the "n_frames" value (the one brought by argv[1]) is lower (tested until 300) the error does not happen and everything goes fine.

When the value is higher (like 1922) the error happens. When the error happens the last printf that is shown is the fourth one, "printf("4\n")".

When the value is 1853 or lower the "printf("5\n")" is shown but the next printf wont show up.

Anyone has any idea what could solve it? What could be the source of Segmentation fault(core dumped) in a so simple step of the program....

Upvotes: 1

Views: 1187

Answers (2)

Drew Hall
Drew Hall

Reputation: 29065

Your frames array is created on the stack using a dynamic size passed in by the user on the command line. You're already out of standard C++ territory here and using an extension/C99ism referred to as "Variable Length Arrays".

Furthermore, the n_frames value you passed in (1922) makes the frames array 1922*377*10 bytes long, i.e. roughly 7.5 MB. On just about any standard desktop/laptop machine/OS, your stack size limit is roughly 1MB, so you're broken in two different ways.

The obvious, direct solution to your problem is to dynamically allocate frames like so:

long double** frames = new (long double*)[n_frames];
for (int i = 0; i < n_frames; ++i) {
  frames[i] = new long double[377];
}

...and of course don't forget the corresponding delete []'s at the end.

However, that said, you'll probably want to learn about std::vector as the de facto dynamically allocated array class in C++.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 613592

This is an stack overflow. You are using a number of variable length arrays (VLA) and for large values of n_frames you overflow the stack. Use dynamically allocated memory instead.

I suspect you did not even realise that you were using VLAs. They are a very easy feature to misuse and unless you really understand the full implications of their use you should avoid them.

Your code looks much more like C than C++. In my view it is time for you to learn how to do things the C++ way. You should really be avoiding raw memory allocation. And you should certainly not be calling printf and never ever call atoi.

Upvotes: 1

Related Questions