strncat上的分段错误()

Kir*_*hou 1 c string heap-memory segmentation-fault

首先,我写了一个简单的程序.

  1 #include <string.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4
  5 int main()
  6 {
  7     char *buf = (char*)malloc(sizeof(char)*2000);
  8     char tmp[256];
  9     strcpy (tmp, "test");
 10     printf ("tmp: %s\n", tmp);
 11     strncat (buf, tmp, strlen(tmp));
 12     printf ("buf: %s\n", buf);
 13 }
Run Code Online (Sandbox Code Playgroud)

预期的结果是:

tmp: test
buf: test
Run Code Online (Sandbox Code Playgroud)

但是在我的大项目中合并代码之后.(使用大量堆段)

153     char *inbuf = (char*)malloc(sizeof(char)*2000);
154     char *outbuf = (char*)malloc(sizeof(char)*2000);
155     char *oldinbuf = (char*)malloc(sizeof(char)*2000);
156     char *errbuf = (char*)malloc(sizeof(char)*2000);
157     memset (inbuf, '\0', strlen(inbuf));
158     memset (oldinbuf, '\0', strlen(oldinbuf));
159     memset (errbuf, '\0', strlen(oldinbuf));
Run Code Online (Sandbox Code Playgroud)

然后在第11行中,我收到错误消息 Segmentation fault (core dumped)

是否存在strncat导致段故障的可能性?

das*_*ght 6

此行具有未定义的行为

strncat (buf, tmp, strlen(tmp));
Run Code Online (Sandbox Code Playgroud)

因为buf来自malloc未初始化.strncat另一方面,期望buf包含以null结尾的C字符串.

您可以通过设置bufto 的初始字符来解决此问题'\0'.