使用 strcat 的分段错误 [英] Segmentation fault using strcat
问题描述
这是我的代码:
char *name, name_log="log-";
------从用户那里得到名字"-----
------getting 'name' from user-----
strcat(name_log, name);
char ext[] = ".log";
strcat(name_log, ext);
我最终需要的是 name_log = "log-'name'.log" 但我得到一个分段错误错误:((.我做错了什么,我该如何解决它?谢谢
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
推荐答案
首先,如果 this 是您的代码:
For a start, if this is your code:
char *name, name_log="log-";
那么 name_log
是 char, 不是 char 指针.
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.
对于可变大小的字符串,就像 user
看起来那样,可能最安全的选择是分配另一个足够大的字符串来保存结果,例如:
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屋!