[英]Negative input crashes program
I have the following function:我有以下 function:
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *substr;
if (!s)
return (NULL);
if (start > ft_strlen(s))
len = 0;
if (start <= ft_strlen(s) && s[start] != '\0')
{
if (ft_strlen(s + start) < len)
len = ft_strlen(s + start);
}
substr = (char *)malloc(sizeof(*s) * (len + 1));
if (!substr)
return (NULL);
if (len == 0)
return (substr);
ft_strlcpy(substr, s + start, len + 1);
return (substr);
}
Some of the functions are self-made (strlen = ft_strlen etc).一些功能是自制的(strlen = ft_strlen 等)。
The problem: if I pass in -1 for "start", my program segfaults because it is converted to 4.294.967.295.问题:如果我为“开始”传递 -1,我的程序会出现段错误,因为它被转换为 4.294.967.295。 So it crashes when passed in that is my function body does not even execute making all protective measures useless.所以它在传入时崩溃,我的 function 身体甚至没有执行,使所有保护措施都无用。 Even stranger, if I execute this on my Mac everything works fine, on Ubuntu 22.04 it does not.更奇怪的是,如果我在我的 Mac 上执行此操作,一切正常,但在 Ubuntu 22.04 上却没有。
Any suggestions?有什么建议么? I am not allowed to change the function prototype.我不允许更改 function 原型。
Edit: I have to pass a series of tests and the following one I am failing constantly:编辑:我必须通过一系列测试,而以下测试我经常失败:
Error in test 4: ft_substr("hola", 4294967295, 0): Segmentation fault!
(The test actually inputs -1). (测试实际输入-1)。
Also, I am not allowed to include a main that tests user input.此外,我不允许包含测试用户输入的主要内容。
Edit 2: My main is simple and just calls the function with input "hola", -1, 3编辑 2:我的 main 很简单,只需调用 function 输入“hola”,-1、3
You need to terminate the string you've copied with ft_strlcpy
with '\0'
.您需要使用'\0'
终止使用ft_strlcpy
复制的字符串。 Your bounds checking could also be made a little simpler.您的边界检查也可以变得更简单一些。
Example:例子:
char *ft_substr(char const *s, unsigned int start, size_t len)
{
if (!s) return NULL;
size_t slen = ft_strlen(s);
if (start > slen) { // start out of bounds, make empty string
start = 0;
len = 0;
} else if(start + len > slen) { // len is too large, shrink it
len = slen - start;
}
char *substr = malloc(len + 1);
if (!substr) return NULL;
ft_strlcpy(substr, s + start, len); // note: copy len, not len+1
substr[len] = '\0'; // terminate the string
return substr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.