因此,我的任务是创建并返回给定字符串的副本,以防它失败(例如,按enter键)返回NULL。然而,当我按回车键时,程序继续工作,并打印出一些无用的值。有趣的事实是,当我通过调试器运行程序时,它工作得很好(这是最让我兴奋的)。我找不到一个简单的解释来解释可能出了什么问题。或者是我的编译器有问题?
#include <stdio.h>
#include <stdlib.h>
// listing functions
char *ft_strdup(char *src);
int main(void)
{
// input of a string
char c[200];
scanf("%[^\n]%*c", c);
// calling a function
char *f = ft_strdup(c);
printf("\n%s\n", f);
free(f);
return 0;
}
char *ft_strdup(char *src)
{
int i = 0;
// itearting to get the 'length' of string src
while (src[i] != '\0')
++i;
// if user has inputted nothing - return NULL and break the function
if (i == 0)
{
return NULL;
}
// otherwise, make a copy of the string
char *x = malloc(i+1);
int j = 0;
while (j != i)
{
x[j] = src[j];
++j;
}
x[i+1] = '\0';
// print out and return
printf("%s\n%s\n%i", x, src, i);
return x;
}发布于 2020-02-12 21:00:34
由于两个原因,程序具有未定义的行为。
第一个问题是数组c未初始化
char c[200];因此它有不确定的值,如果用户只按Enter键,数组将不会改变。
您可以在C++中对其进行初始化,如下所示
char c[200] = {};或在C中,如
char c[200] = { '\0' };或者就像这样
char c[200] = "";;
第二种方法是访问函数ft_strdup中分配的数组之外的内存。
x[i+1] = '\0';你必须要写
x[j] = '\0';你必须检查函数的返回值。
请注意,在C++中,您应该使用操作符new和delete,而不是C函数malloc和free。您应该使用标准的C++类std::string,而不是动态创建字符数组来存储字符串。
https://stackoverflow.com/questions/60188822
复制相似问题