Segmentation fault error - C programming
<p>I am receiving a Segmentation Fault error when I run this program. To summarize, the program reads in multiple data files (129 of them). Each file contains information about a specific name. The information includes how many people were named a specific name in a specific year and the gender. For now, I am trying to store each name in a linked list. Whenever I read in more than about 4 data files, I get the Segmentation Fault error. I have written this program in Java, which was much simpler. If anybody could simply point me in the right direction, as I am almost certain this has to do with memory allocation, but I cannot seem to solve this myself. Thank you.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;cstdlib&gt;
using namespace std;

//typedef struct Node NodeStruct;
struct Node {
  char *namePtr;
  Node *nextPtr;
};

int main() {
  // Declare variables 
  Node *headPtr = NULL;
  Node *tempPtr;
  Node *currentPtr;

  // Variables for reading in a file
  FILE *filePtr;
  char fileName[20];
  int i;
  int nameLength;
  char inputLine[81];

  cout &lt;&lt; "Reading from data files, please be patient...\n";

  // Loop through files
  for (i = 1880; i &lt;= 2009; i++) {
    sprintf(fileName, "data/yob%d.txt", i);
    filePtr = fopen(fileName, "r");    // Open the file
    // Check to ensure file was opened
    if(filePtr == NULL) {
      cout &lt;&lt; "Error opening input file...check location of data files\n";
      exit(-1);   // Exit program
    } // End if statement

    while (fscanf(filePtr, "%s", inputLine) != EOF) {

      // Create a node
      tempPtr = (Node *) malloc(sizeof(Node));
      tempPtr-&gt;nextPtr = NULL;

      // Set the head pointer of first node
      if (headPtr == NULL) {
    headPtr = tempPtr;
    currentPtr = tempPtr;
      } // End if statement

      // Link the list
      currentPtr-&gt;nextPtr = tempPtr;
      currentPtr = currentPtr-&gt;nextPtr;

      // Create pointer variables
      char *startPtr = inputLine;
      char *endPtr = NULL;

      endPtr = strchr(inputLine, ',');   // Point to end of name
      int length = endPtr - inputLine;      // Calculate length
      // Create space for the name
      tempPtr-&gt;namePtr = (char *) malloc(sizeof(length + 1));
      strncpy(tempPtr-&gt;namePtr, startPtr, length); // Store pointer to name
      //      cout &lt;&lt; tempPtr-&gt;namePtr &lt;&lt; endl;

    }
  } // End of for (i = 1880...
  cout &lt;&lt; "Done reading from data files...\n";
} // End of main function
</code></pre>
