Today I helped my friend with some C code, and I found strange behavior that I could not explain to him why this was happening. We had a TSV file with a list of integers, with int each line. The first line was the number of lines that had a list.
We also had a c file with a very simple "readfile". The first line was read in n, the number of lines, then there was initialization:
int list[n]
and finally a for loop from n with fscanf.
For small n (up to ~ 100,000) everything was in order. However, we found that when n was large (10 ^ 6), segfault will occur.
Finally, we changed the initialization of the list to
int *list = malloc(n*sizeof(int))
and all when good, even with very large n.
Can someone explain why this happened? what caused segfault with int list [n], which was stopped when we start using list = malloc (n * sizeof (int))?
c arrays malloc variable-length-array
JC LeitΓ£o May 13 '12 at 9:52 pm 2012-05-13 21:52
source share