【发布时间】:2015-01-20 11:29:45
【问题描述】:
首先,我编写一个简单的程序。
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 }
预期结果是:
tmp: test
buf: test
但是在我将代码合并到我的大项目中之后。 (使用很多堆段)
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));
然后在第 11 行,我收到错误消息Segmentation fault (core dumped)
strncat有没有可能导致段错误?
【问题讨论】:
-
因为我需要将
buf中的旧内容和tmp中的新内容串联起来,并且我仔细检查了inbuf中的旧内容(在malloc大小内)。 -
我们没有看到
buf在strncat()之前被初始化为任何值,这就是您看到问题的原因。如果 buf 在strncat之前有一些价值,那么这将可以正常工作。因此,如果是这种情况,您可以使用strncpy() -
您可以使用
callocwhich may be faster anyway 而不是malloc + memset。您在第 157-159 行的memset设置为 wrong number of bytes。也 see here 用于 malloc 的现代用法。 -
你的问题不清楚,你是在你的测试程序中得到了段错误,还是在你的“真实代码”中,或者在 bith 上?
-
在编辑后的代码中,段错误将来自使用
strlen在第 157-159 行的未初始化内存上。请编辑您的帖子;它说你在第 11 行得到了段错误,但实际上你没有。确保您发布的代码确实存在问题。
标签: c string segmentation-fault heap-memory