bullinka
bullinka

Reputation: 13

Strcpy() - Segmentation fault in C

I am working on a lab assignment and we need to create a dictionary to hold some words and their pirate-speak equivalent. I am able to read the file in, separate the words out as shown by the sscanf function, but I'm getting a segmentation fault when I use strcpy to store each word in their respective array: strcpy(&eng[i], englishWord);

I do not understand how to correct this problem. (Sorry if my code is ugly. This is my first time programming in C.)

void CreateDictionary( char eng[], char pir[] ){
  char word[40];
  FILE* dictionary;

  const char *pirateWord;
  const char *englishWord;

  dictionary = fopen("english-to-pirate.txt", "r");
  if (dictionary == NULL){
    printf("Unable to open the dictionary file.\n");
  }
  else{
    //Setup dictionary
    int i = 0;

    while(fgets(word, sizeof word, dictionary) != '\0'){   
      //Split line using semicolon
      sscanf(word,"%[^;];%[^;]", englishWord, pirateWord);
      printf("%s : %s",englishWord, pirateWord);

      //put term in corresponding array
      strcpy(&eng[i], englishWord); //seg fault occuring here

      strcpy(&pir[i], pirateWord);
      i++;  
    }
  }
  fclose(dictionary);
}

This is where the function is being called:

int main( ) {
  char inFileName[100];
  char outFileName[100];
  FILE* inFile;
  FILE* outFile;
  char english[75] = {[0 ... 74] = '\0'};
  char pirate[75] = {[0 ... 74] = '\0'};

  CreateDictionary(english, pirate);

  return 0;
}

Upvotes: 0

Views: 160

Answers (2)

Chris VanWyk
Chris VanWyk

Reputation: 93

You must have memory (and enough memory) allocated for the destination pointer in strcpy. Without seeing the calling code for CreateDictionary, it's not possible to diagnose what went wrong.

If the calling code doesn't allocate memory for eng[], you could consider using strdup instead of strcpy. strdup will allocate the enough memory to hold the string.

Upvotes: 0

chux
chux

Reputation: 153338

There is no assigned memory associated with englishWord, pirateWord in which to put the scanned data.

Use char pirateWord[sizeof word]; char englishWord[sizeof word];

Always good to check the result of sscanf()

if (2 != sscanf(...)) FailedToScan();

Upvotes: 1

Related Questions