使用strcat的分段故障 [英] Segmentation fault using strcat
问题描述
下面是我的code:
char *name, name_log="log-";
从------用户使用'名'-----
------getting 'name' from user-----
strcat(name_log, name);
char ext[] = ".log";
strcat(name_log, ext);
我需要到结束是name_log =登录'name'.log但是我得到一个分段错误:((我是什么做错了,我怎么能解决这个问题THX
What i need to end up with is name_log = "log-'name'.log" but Im getting a segmentation fault error :((. What am I doing wrong and how can I fix it ? Thx
推荐答案
首先,如果的这个的是你的code:
For a start, if this is your code:
char *name, name_log="log-";
然后 name_log
是字符,的不是一个字符指针。
then name_log
is a char, not a char pointer.
假设这是一个错字,你不能追加到字符串这样。修改字符串是未定义的行为。
Assuming that's a typo, you cannot append to string literals like that. Modifications to string literals are undefined behaviour.
有关大小可变的字符串,如用户
似乎是,这可能是最安全的选择是分配另一个字符串大到足以容纳的结果,是这样的:
For a variable sized string, as user
appears to be, probably the safest option is to allocate another string large enough to hold the result, something like:
char *name, *name_log = "log-", *ext = ".log";
// Do something to allocate and populate name
char *buffer = malloc (strlen (name_log) + strlen (name) + strlen (ext) + 1);
if (buffer == NULL) {
// Out of memory.
} else {
strcpy (buffer, name_log);
strcat (buffer, name);
strcat (buffer, ext);
// Do something with buffer.
free (buffer);
}
的的malloc
确保你有足够的空间来完成所有的字符串操作安全,足够的字符为三个组成部分加一个空终止符。
The malloc
ensures you have enough space to do all the string operations safely, enough characters for the three components plus a null terminator.
这篇关于使用strcat的分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!