首页 > 解决方案 > How do strcat() and read() work with '\0' in C

问题描述

here's my whole code first :

 1. #include <stdio.h>
 2. #include <stdlib.h>
 3. #include <unistd.h>
 4. #include <sys/wait.h>
 5. #include <string.h>
 6. int main(int argc, char *argv[]) {
 7.     int p[2]; // p[0]: file descriptor for read end of pipe
 8.               // p[1]: file descriptor for write end of pipe
 9.     if (pipe(p) < 0) exit(1);
 10.    int rc1 = fork();
 11.    if (rc1 < 0){ fprintf(stderr, "fork error\n"); }
 12.    else if (rc1 == 0){ write(p[1], "1st child output",
 13.                              sizeof("1st child output")); }
 14.    else{
 15.        int rc2 = fork();
 16.        if (rc2 < 0){ fprintf(stderr, "fork error\n"); }
 17.        else if (rc2 == 0){
 18.            printf("2st child output\n");
 19.            char *_1st_child_out;
 20.            read(p[0], _1st_child_out, sizeof("1st child output"));
 21.            strcat(_1st_child_out, ", AFTER PIPE YA FOOL");
 22.            printf("%s\n", _1st_child_out);
 23.        }
 24.    }
 25. }

if i initialize 19:13:

char *_1st_child_out;

with a '\0' or NULL, the string stays empty and 22:13:

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

prints nothing, so how do strcat() and read() work? should i not insert any null terminators before invoking them? what about garbage values?

标签: cnullpipestrcat

解决方案


Your line 19 has a pointer that is not pointing to any allocated memory. Change it to a char array will fix the problem.

char _1st_child_out[100];

Also, for security, don't use strcat. All str function such as strcpy etc does not check destination boundary. They all have an n version. strcat should be replaced with strncat, which will take a third parameter to specify max length of cat so buffer overflow will not happen.


推荐阅读