0
$ ls
baby.txt      readlyrics.c

I tried to write a simple program to print the text from a .txt file using nanosleep() to get some sort of animated effect:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>


int main(int argc, char *argv[]) {

    char *target_file = argv[1];
    char *sec     = argv[2];
    char *nsec     = argv[3];

    int   tv_sec  = atoi(sec);
    float tv_nsec = atof(nsec);

    struct timespec *t;
    t->tv_sec  = tv_sec;
    t->tv_nsec = (long)(tv_nsec * 1000000000);

    FILE *content = fopen(target_file, "r");
    int *c  = malloc(sizeof(char));
    c       = NULL;
    c = fgetc(content);
    while(c) {
        printf("%c", c);
        c = NULL;
        nanosleep(t, NULL);
        c = fgetc(content);
    }
    fclose(content);

    return 0;
}

And got an error:

$ ./read ./baby.txt 0 0.01
zsh: segmentation fault  ./read ./baby.txt 0 0.01

Which part of the code went wrong?

init 1
  • 39
  • 6
  • 1
    Build with debug information (add the `-g` flag when building). Then run in a debugger to catch the crash and locate exactly where in your code it happens. Then you can also examine variables and their values to see if they give come hints. – Some programmer dude May 21 '21 at 04:05
  • 2
    By the way, all your fidling with `c`, making it a pointer, and all its reassignment, and then treating it as an actual `char` instead of a pointer to one, that tells me that you need to spend more time with your text-books to read about pointers, and more importantly read about `fgetc` and what it returns. You seem to have some basic misunderstanding about reading characters from files. – Some programmer dude May 21 '21 at 04:07
  • `while(c)` is wrong. `fgetc` does not return `0` or `NULL` at end of file. You need to declare `c` as an `int` and compare it against `EOF`. Note that `EOF` is generally defined as `-1` and hence evaluates to true when used in a boolean condition. – kaylum May 21 '21 at 04:30

1 Answers1

0

I think I know the answer now... Aside from variable c, I declared t as a pointer and it was not initialized, after changing struct timespec * to struct timespec I solved the problem. I think it's because it relies on the user's input to get itself initialized.

init 1
  • 39
  • 6
  • 1
    The whole mess with `c` overshadowed that you use the pointer `t` without making it point anywhere. But this issue would have been found out by enabling more warnings when building, as GCC typically is able to catch such problems. – Some programmer dude May 21 '21 at 07:28