There is a code:

#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> bool strbegin(const char *, const char *); int main(int argc, char const *argv[]) { FILE * src_file = fopen(argv[1], "r"); char * buf_str = malloc(1024 * sizeof(char)); while (fgets(buf_str, sizeof(buf_str), src_file)) { if (strbegin(buf_str, "#")) printf("This string begin with '#': \n%s", buf_str); } fclose(src_file); return 0; } bool strbegin(const char * _str, const char * _begin) { for (int i = 0; i < strlen(_begin); ++i) { if (_begin[i] != _str[i]) return false; } return true; } 

This code prints a line that starts with a # character.

File contents:

 // ex1.ar #include <stdio> 

Here is the output of the program:

 This string begin with '#': #in 

If instead

printf("This string begin with '#': \n%s", buf_str);

Write

 printf("This string begin with '#': \n"); printf("%s", buf_str); 

The result is the same. And outside the condition if lines are printed completely. The function strbegin does not contain errors - it checked. I just can not understand why the error seems to be all right.

I compile this way: clang-3.8 src/main.c -o bin/main -Wall -pedantic

I ./bin/main example/ex1.ar : ./bin/main example/ex1.ar

    1 answer 1

    Error in using sizeof . sizeof(buf_str) returns the pointer size, i.e. 4 bytes.

      fgets(buf_str, 1024, src_file);