strcat 实现
我尝试自己实现 strcat,并从 Wiki 找到了 strcat 实现,如下所示。 ....但是当我使用它时,出现分段错误。
下面的代码有什么问题?
char *
strcat(char *dest, const char *src)
{
size_t i,j;
for (i = 0; dest[i] != '\0'; i++)
;
for (j = 0; src[j] != '\0'; j++)
dest[i+j] = src[j];
dest[i+j] = '\0';
return dest;
}
I tried to implement the strcat by myself, and I found the strcat implementation from Wiki like this......but when I use it, there is segmentation fault.
What's wrong with the code below?
char *
strcat(char *dest, const char *src)
{
size_t i,j;
for (i = 0; dest[i] != '\0'; i++)
;
for (j = 0; src[j] != '\0'; j++)
dest[i+j] = src[j];
dest[i+j] = '\0';
return dest;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
代码没问题。
看来您的调用代码有问题。
您是否记得为目标字符串分配足够的内存?
the code is okay.
Looks like you have a problem in the calling code.
Did you remember to allocate enough memory for the target string?
我强烈建议使用指针而不是整数索引,因为担心整数溢出。即使
size_t
与char *
的位数相同,您也会在不添加指针的地方添加索引。我想这或多或少是学术性的;如果您在数 GB 字符串上调用
strcat()
,您可能会遇到各种麻烦。为了完整起见,这是一个基于指针的版本:
当然,这确实需要另一个指针的空间来存储
rdest
返回值,但我认为这是一个很好的权衡。另请注意,您无法在普通应用程序代码中合法地定义名为
strcat()
的函数;整个命名空间(名称以str
开头的公共函数)被保留用于实现。I would strongly suggest using pointers rather than integer indexes, for fear of integer overflow. Even if
size_t
is the same number of bits aschar *
, you're adding indices where you wouldn't be adding pointers.I guess that's more or less academical; if you're calling
strcat()
on multi-gigabyte strings you're probably in all sorts of trouble.Here's a pointer-based version, for completeness' sake:
Sure, this does take another pointer's worth of space for the
rdest
return value, but I think that's a fine trade-off.Also note that you can't legally define a function called
strcat()
in ordinary application code; that whole namespace (public functions with names starting withstr
) is reserved for the implementation.dest 需要有足够的内存来容纳此实现中的串联。在此实现中,它必须由调用者分配。您还应该确保 dest 和 src 都以 null 结尾。如果 dest 没有足够的内存,这将覆盖可以被其他东西使用的内存。
dest needs to have enough memory to accommodate the concatenation in this implementation. In this implementation, it would have to be allocated by the caller. You should also be sure both dest and src are null terminated. If dest does not have enough memory, this will overwrite memory that could be used by something else.
它对我来说工作正常,我已经检查过。
Its working fine with me, I have check it.
为目标字符串分配足够的内存..即至少(源字符串的长度+ 1)。
Allocate enough memory for the destination string.. ie atleast (length of source string + 1).