Thread: Reading a txt file into an array: unexpected segfault

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    7

    Reading a txt file into an array: unexpected segfault

    Hi to all!

    I have this function that, provided with a target array of strings and a file name, reads it line by line and stores the lines into the given array

    Code:
    void file_to_array(char **target_lines, char *file_name)
    {
    	FILE *f;
    	char line[LINE_SIZE];
    	int num_righe = 0;
    	
    	f = fopen(file_name, "r");
    	/* crea il file se non lo trova */
    	if(f == NULL) {
    		f = fopen(file_name, "w");
    	}
    	
    	while(fgets(line, LINE_SIZE, f)) {		
    		num_righe++;
    		target_lines = (char**)realloc(target_lines, (sizeof(char*)*num_righe));
    		target_lines[num_righe-1] = strdup(line);
    	}
    
    	fclose(f);
    }
    Calling it like follows it gives me a Segmentation fault in the line where I try to print the second item.

    Code:
    char **lines = NULL;
    file_to_array(lines, "spese.dat");
    printf("%s", lines[0]);
    The file is correct and outputting like by line within the function ( printf("%s", target_lines[num_righe-1]) ) gives the correct lines.

    Any help?
    Thanks in advance
    Last edited by pistacchio; 05-05-2009 at 01:14 PM. Reason: colored the faulting line

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading from a file into an array
    By fmsguy06 in forum C Programming
    Replies: 6
    Last Post: 10-18-2008, 09:25 PM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. reading from file to an array - help needed!
    By timeforheroes in forum C Programming
    Replies: 2
    Last Post: 04-28-2005, 12:16 PM
  4. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM

Tags for this Thread