Thread: Import data of file; error message "segmentation fault"

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2016
    Posts
    1

    Import data of file; error message "segmentation fault"

    Dear all,

    the problem with my code is that I get always the error message "segmentation fault". I import data of a file and I want to use the data to do some calculations. This is not possible because of the "segmentation fault" message. The imported data look like this:

    4434.853080
    3638.536464
    3638.779956
    3639.006619

    The C code is the following:

    Code:
    #include<stdio.h>
    #include<math.h>
    #include<stdlib.h>
    #include<string.h>
    
    int main (void){
    
    FILE *fp = fopen("file.txt","r");
    
    //first wanted to get the number of lines
    size_t nbytes;
    ssize_t read;
    char *my_string;
    int fr=0;
    while((read=getline(&my_string, &nbytes, fp)) !=-1){
            fr++;}
    printf("this is the number of lines in the given file : %d \n", fr);
    fclose(fp);
    
    my_string=(char *) malloc (fr);
    
    //here I open the file again for my calculations
    FILE *fpp=fopen("file.txt","r");
    int ii=0;
    double *s;
    
    
    s=(double *) malloc (fr);
    while((read=getline(&my_string, &nbytes, fpp)) !=-1){
            my_string[ strlen(my_string)-1 ]=0;
            s[ii]=atof(my_string);
            ii++;}
    
    fclose(fpp);
    free(my_string);
    
    
    return 0;
    }
    Here I get the segmentation fault error message. The question is why I get this message and what to do?
    ( I want to do further calculations and this is not possible with the segmentation fault.)
    Last edited by usingC; 07-28-2016 at 03:05 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why do I get the error message "Segmentation fault"?
    By howardbc14 in forum C Programming
    Replies: 5
    Last Post: 04-25-2015, 11:47 PM
  2. "Segmentation Fault: 11" error message
    By avolkmar in forum C Programming
    Replies: 6
    Last Post: 11-09-2012, 12:09 PM
  3. Replies: 5
    Last Post: 04-10-2012, 02:31 PM
  4. Replies: 2
    Last Post: 10-31-2011, 11:57 AM
  5. Segmentation fault by fopen(file,"r")
    By Stefan in forum C Programming
    Replies: 3
    Last Post: 02-12-2006, 04:37 AM

Tags for this Thread