-1
#include <stdio.h>
#include <string.h>

int main()
{
    //read any text file
    char const* const fName = "database-large.txt";
    FILE* fp = fopen(fName, "r");
    
    char *ptr;
    char substr[5000];
    long i=0, j=0;

    // if file not opened
    if(!fp){
        printf("\n Error in open : %s ", fName);
        return -1;
    }

    // to strore each line
    char line[5000];

    // read line by line
    while (fgets(line, sizeof(line), fp)) {
        //to extract mailid in between "From:" and "\n"
        ptr = strstr(line, "Date:");
        i=ptr-line;

        while(line[i] !='\n')
        {
            substr[j] = line[i+9];
            i++;
            j++;
        }
        printf("%s\n", substr);
    }
    
    // to close the file
    fclose(fp);

    return 0;
}

Why does this compile but gives me a segmentation fault when when I run it because of the line "while(line[i] !='\n')".This is the only issue I have when running my code.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

1

You need to check whether strstr returned a null pointer or not. Otherwise the following statement after the call of strstr

            ptr = strstr(line, "Date:");
            i=ptr-line;

can invoke undefined behavior when ptr is equal to NULL.

The second problem is that you do not reset the variable j to 0 in each iteration of the while loop.

And the third problem is that the array substr has to contain a string if you are using the conversion specifier %s in this call

printf("%s\n", substr);

Otherwise you need to write

printf("%.*s\n", ( int )j, substr);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335