Advertisement

segmentation error when using fgets why?

Started by January 05, 2001 06:31 AM
4 comments, last by crazy-vasey 24 years ago
  

char *TileNames[255];

char *MapNames[255];

char *ScriptNames[255];

void ParseTiles()

            {

             FILE *Tiles;

             Tiles = fopen("c:\\game\\tiles.ini","rt");

             if (!Tiles) {printf("cannot find tiles.ini!\nexiting..."); exit(-1);

             for(int i=0;i<255;i++)

                     {

                      fgets(TileNames[i],255,Tiles);

                     }

          fclose(Tiles);

          }
               }
void ParseMaps()

      {

      FILE *Map;

      Map = fopen("c:\\game\\maps.ini","rt");

      if(!Map) {printf("Cannot find maps.ini\nExiting..."); exit(-1);}

      for(int j=0;j<255;j++)

              {

               fgets(MapNames[j],255,Map);

               }

      fclose(Map);

      }

void ParseScripts()

     {

      FILE *Scripts;

      Scripts = fopen("c:\\game\\scripts.ini","rt");

      if(!Scripts) {printf("Cannot find scripts.ini\nExiting..."); exit(-1);}

      for(int i=0;i<255;i++)

              {

               fgets(ScriptNames[i],255,Scripts);

              }

       fclose(Scripts);

       }

  
When I run these three functions in a row I get a segmentation fault on the second function ran when it gets to the fgets. Anybody know why?
Okay for some reason the first functions braces have went to random places just ignore that its right in my code.
Advertisement
You haven't allocated the memory for the TileNames (or the other names), what you want to do is something like:
A)
      char TileNames[255][255];  

or alternatively in the loop:
B)
        for(int i = 0; i < 255; i++){  TileNames[i] = new char[255]; // use malloc() if you prefer it  fgets(TileNames[i], 255, Tiles);}  

Just think that char * is NOT a string it's a pointer to a string, the difference is that char * hasn't got any memory allocated for it, thus the segmentation fault.
Oops, forgot to clarify that the two methods are mutually exclusive, don't use both!!!

/Andreas

Edited by - amag on January 5, 2001 8:01:06 AM

Edited by - amag on January 5, 2001 8:02:30 AM
How did I miss that?! *smacks head* So WTF is a segmentation fault?
Segmentation fault happens under some UN*X-clones (all??) when you try to access memory you do not own (or your process is probably more correct ), which is the case with most uninitialized pointers, since they can point anywhere in memory (or even outside).
thanks for the help

This topic is closed to new replies.

Advertisement