Thread: Reading from file, segmentation fault

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    33

    Reading from file, segmentation fault

    I'm reading text from a file into an array of strings, when I run the program like this everything works fine, but if I comment out the lines "char letter = 'A'" and the printf two lines below it, there is a seg fault. Why is this? That was just to letter the lines, I don't see how this could result in a seg fault.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main(int argc, char *argv[]){
       FILE *file = fopen("file", "r");
       if(file == NULL){
          puts("File not found");
          return 0;
       }
    
    
       char string[100], **array;
       int idx = 0;
       while(idx < 100 && fgets(string, 100, file) != NULL){
          array[idx] = (char*) malloc(strlen(string));
          string[strlen(string) - 1] = '\0';
          strcpy(array[idx++], string);
       }  
    
    
       char letter = 'A';
       for(idx = 0; idx < 5; idx++){
         printf("%c. ", letter++);
          puts(array[idx]);
       }
       fclose(file);
       return 0;
    }

  2. #2
    Registered User
    Join Date
    Mar 2013
    Posts
    31
    Hmm, just wondering why you strcpy your string into an address 1 ahead of the one you just allocated?

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,121
    Well you need to either have
    char *array[100];

    Or allocate all your pointers with say
    array = malloc( 100 * sizeof(*array) );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading from stdin and printing (Segmentation Fault)
    By auxfire in forum C Programming
    Replies: 3
    Last Post: 03-08-2013, 03:33 AM
  2. Segmentation Fault. When trying to open file.
    By guyle in forum C Programming
    Replies: 5
    Last Post: 02-25-2013, 12:55 PM
  3. Segmentation fault reading and parsing data from a text file
    By deathseeker25 in forum C Programming
    Replies: 4
    Last Post: 05-19-2012, 12:33 PM
  4. Segmentation fault when reading very large text files
    By sapogo06 in forum C Programming
    Replies: 8
    Last Post: 12-07-2009, 03:19 PM
  5. Segmentation fault reading integers into an array
    By bolivartech in forum C Programming
    Replies: 4
    Last Post: 10-23-2009, 08:06 PM