我最近试图创建一个重复字符串的函数,例如:ip:"apple"count=5,output:"appleappleappleapple">
char *ch = "apples"
ch = cpy_data(ch, 6, 20);
char *cpy_data(char *ip_str, int in_len, out_len)
{
char *c = malloc(out_len);
memset(c, 0, out_len);
int rem, n;
rem = out_len % in_len;
n = 0;
while(n < out_len){
memcpy(&c[n], ip_str, in_len);
n += in_len;
}
if (rem)
memcpy(&c[n], ip_str, rem);
printf("%s n" c);
return c;
}
OutPut: applesapplesapplesapplesaph�
输出len比预期的输入大得多,并且正在打印一些尾部垃圾数据。
问题中的代码包含大约5个语法错误。最好显示您准确使用的代码。
一旦修复为语法正确的C,您的程序就会尝试向malloc分配的块写入超出容量的数据:https://taas.trust-in-soft.com/tsnippet/t/9c2ce34f
Frankie_C在评论中指出,您可能希望为最终的' '
保留空间,但这不足以定义程序:还有一个逻辑错误,即只要还有一个字符的空间,程序就会尝试复制更多的in_len
字符:https://taas.trust-in-soft.com/tsnippet/t/3a2b848b
我把循环条件改为while (n < out_len - rem) {
,就像Karthick的回答一样。现在的问题是,传递给printf("%s"
的字符数组并没有以最终的' '
结束:https://taas.trust-in-soft.com/tsnippet/t/7c1ca032
必须编写最终的'0'
。由于目标块是由malloc
分配的,并且不能保证0初始化,因此不足以在末尾为字符留出空间。您还必须显式地将最后一个字符设置为' '
,例如使用:
c[out_len] = ' ';
最后,不产生未定义行为的程序的修改版本是(https://taas.trust-in-soft.com/tsnippet/t/dea9e8b2(:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *cpy_data(char *ip_str, int in_len, int out_len)
{
char *c = malloc(out_len + 1);
memset(c, 0, out_len);
int rem, n;
rem = out_len % in_len;
n = 0;
while(n < out_len - rem){
memcpy(&c[n], ip_str, in_len);
n += in_len;
}
if (rem)
memcpy(&c[n], ip_str, rem);
c[out_len] = ' ';
printf("%s n", c);
return c;
}
int main(int argc, char **argv) {
char *ch = "apples";
ch = cpy_data(ch, 6, 20);
}
您的程序很少有问题
1( 您的while
循环使您的内存能够访问超出您分配的内存。所以让你的时间看起来像while(n < out_len-rem){
2( 字符串应始终以