c - 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?
解决方案
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.
推荐阅读
- c# - 连接到应用程序池丢弃 IIS
- excel - 将 CSV 文件转换为 XLSX 的 Shell 脚本
- gruntjs - 执行“咕噜”命令会引发“访问被拒绝”错误
- ftp - 无法从 Azure 数据工厂访问 FTP 服务器上的文件
- symfony - 覆盖模板电子邮件 FOSUserBundle
- sql - SQL 链接服务器连接适用于服务器上的 Windows Authenticatoin,但不适用于工作站
- python - 烧瓶登录页面无法使用谷歌帐户登录
- delphi - 清单和 GetVersionEx
- c - 在 C 中使用队列的二叉树级顺序遍历
- javascript - javascript:获取从 ajax 请求返回的值