-2
int main(void){
char* line = "CCCCCCC\nC+\nC++";
char* line2 = "a\nb\nc";
//char* pattern = ".\\+\\+";
//int n= strlengp(line);
printf("%s\n", line);
printf("%s\n", line2);
fputs(line, stdout);

This code correctly prints: CCCCCCC

C+

C++

a

b

c

Now my issue is this, I am working on rgrep function implemented without string.h. Below is the main from the code im working on, which I am not to modify.

int main(int argc, char **argv) {
   if (argc != 2) {
        fprintf(stderr, "Usage: %s <PATTERN>\n", argv[0]);
        return 2;
    }

    /* we're not going to worry about long lines */
    char buf[MAXSIZE];

    while (!feof(stdin) && !ferror(stdin)) {
        if (!fgets(buf, sizeof(buf), stdin)) {
            break;
       }
       if (rgrep_matches(buf, argv[1])) {
           fputs(buf, stdout);
           fflush(stdout);
       }
   }

    if(ferror(stdin)) {
       perror(argv[0]);
       return 1;
   }

   return 0;
}

int rgrep_matches(char *line, char *pattern){
   printf("%s", line);
   return 0;
}

Now when I run the above code on test test file containing the same strings as the above code "CCCCCCC\nC+\nC++","a\nb\nc".

Whys does the above code output:

CCCCCCC\nC+\nC++

a\nb\nc

Clearly ignoring the '\n'.

When the test code built in a different file posted at the top of the page prints:

CCCCCCC

C+

C++

a

b

c

What is going on here?

  • 2
    Here `string[i] = '\0';` trying to modify the read-only memory. So, the behaviour is undefined. – H.S. Oct 26 '17 at 14:20

1 Answers1

2

This causes undefined behavior, because you attempt to write into a non-modifiable memory!!

This line

 string[i] = '\0';

is the culprit here.

To get a workaround, make the string an array, like

char string[] = "a\nb\nc";

which allows the target to be modifiable.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261