segmentation fault.

This code is causing a segmentation fault and I can't figure out why. I'm new to UNIX and I need to learn how to avoid this segmentation fault thing. Thank you so much. Thanks also for the great answers to my last post.:):b:

int main()
{
  mysqlpp::Connection conn(false);

  if (conn.connect("dsgsports","127.0.0.1" , "root", "")) {
          printf("Connected to database.\n");
  }
  else {
    printf("Failed to connect to database.");
    return 1;
  }

  FILE *pFile;
  pFile = fopen("/tmp/headend.txt","r");

  if(pFile != NULL)
  {
    int cnt=0;
    char output[4000000][1000];

    while((fgets(output[cnt],1000,pFile))!=NULL)
    {
      std::cout << output[cnt] << "\n" << endl;
      cnt++;
    }
  }
  else
  {
    std::cout << "Could not open file.\n" << endl;
  }

  outputToImport("aa","aa", &conn);
  return 0;
}

Well, you're going to run out of new and interesting ways to cause it soon, I'm sure... :wink:

It's not a UNIX thing, either. You'd be getting these same crashes on Windows for the same reasons, though it might call them something else.

What "segmentation fault" means is you're trying to use memory you don't have. Of all possible addresses from 0 to 0xffffffff (on 32-bit) only a small bit of those are actually valid -- those your program has asked for or been granted on load.

char output[4000000][1000];

That's a three gigabyte variable! Almost four, even. :eek: There's no way the system is going to let you have a local variable so big. On a 32-bit system it might not even be possible to get that much memory in one process by any means. So when it tries, it reaches gigabytes beyond the maximum address the OS is willing to give it, and bingo: segmentation fault.

Try something a little more modest. char output[1024][1024]; That's exactly one megabyte.

---------- Post updated at 10:00 PM ---------- Previous update was at 09:26 PM ----------

std::cout << output[cnt] << "\n" << endl;

This is redundant since the strings read in by fgets() already have a \n on the end.

std::cout << output[cnt];

Thank you so much! Thanks to your post I figured out I need to be using a vector. You guys are it!

Using or not using a vector has nothing to do with your crash. It crashed because you asked it to allocate an entire 3 gigs of memory. A vector will have a higher limit than a local variable, but it'll probably crash too if you told it to allocate 3 gigs of memory.