0

I am new to programming and wonder why I get a Segmentation Fault when I declare a character array on the stack and not when I do it on the heap.I looked up the article for Stack vs Heap allocation but do not see why this would fail.

The below gives the segmentation fault on the memset

char space[(2*len + 1) * cnt];
memset(space, 0, (2*len + 1) * cnt);

The below works fine

char *space = (char *)malloc((2*len + 1) * cnt);
memset(space, 0, (2*len + 1) * cnt);

In my case len = 999 and cnt = 9999. I am guessing the large memory allocation might be a reason caused by possible stack fragmentation ?

PeterJ
  • 35
  • 1
  • 8

1 Answers1

1

Are you running on a small platform where the available stack space is less than (2*999+1)*9999 = 19,988,001 bytes? Or maybe your compiler defaults to a stack smaller than that? For example, this thread says that Visual Studio's default stack size is only 1MB: C/C++ maximum stack size of program.