0

this might seem silly, but I have the following:

long N = 4169;
long L = 1000;
char Nseq[N][L];

When I run the program with this and more code, I get 'segmentation fault'. Using gdb and seen the info locals I saw this:

Nseq = <error reading variable Nseq (value requires 4169000 bytes, which is more than max-value-size)>

The way I access it in a loop for n<N:

  while (fgets(line, lenline, myfile) != NULL) {
      token = strtok(line, s);
      while (token != NULL && n<N) {
          strcpy(Nseq[n], token);
          //printf("%s\t%u\n", token, n);
          token = strtok(NULL, s);
          n++;
      }

How do I fix it? thank you! and yes, I am a beginner.

fati
  • 29
  • 4
  • 3
    @MichaelBianconi I don't think that question answers this. The size of an automatic array is generally much more limited than static and dynamically-allocated arrays, but that doesn't seem to be mentioned there. – Barmar Jun 22 '20 at 23:57
  • 1
    The important thing here is the size limits placed on automatically allocated arrays on the stack, rather than the heap — clearly an ~4MB array is not that big in general. It's just too big for the stack and needs to be dynamically allocated (`malloc`) on the heap. For the difference between the stack and heap, see https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap. – Linuxios Jun 23 '20 at 00:00
  • That looks like you are accessing the array `Nseq` out of bounds. Since you do not show how you are accessing the array `Nseq`, it is impossible for me to tell you more. You may want to provide a [mre]. – Andreas Wenzel Jun 23 '20 at 00:02
  • Is `char Nseq[N][L];` declared at file scope or at function scope? I.e. is it a global variable or a local variable? As stated by @Linuxios, 4MB is not much space on a modern computer for heap storage, but it is quite a lot for stack storage. – Andreas Wenzel Jun 23 '20 at 00:04
  • I think it is a local variable since it is declared right after the main function is opened. I think I needed it to be that way since I modify the variable during the course of the program – fati Jun 23 '20 at 00:35
  • 1
    @fati no, [avoid global variables](https://stackoverflow.com/q/484635/995714). Allocate on heap instead. [Why global variables are evil](https://www.learncpp.com/cpp-tutorial/why-global-variables-are-evil/) – phuclv Jun 23 '20 at 00:37
  • I can't manage to use malloc, I get so many errors because of the type pf Nseq:error: conflicting types for ‘Nseq’, error: variably modified ‘Nlen’ at file scope, error: subscripted value is neither array nor pointer nor vector strcpy(Nseq[n], token)... and so on – fati Jun 23 '20 at 00:44
  • Please [edit] your question and add the source that gives you errors with `malloc()`. Please remember, a [example] will help to get you answers. – the busybee Jun 23 '20 at 06:01

0 Answers0