[英]Function not returning NULL
我正在尝试编写一个函数,该函数返回从初始函数参数复制的指针,但在开头和结尾('','\\ n','\\ t')不带空格。
char *ft_strtrim(char const *s)
{
unsigned char *p;
int start;
int end;
size_t index;
start = 0;
end = ft_strlen(s) - 1;
while (s[start] == '\n' || s[start] == '\t' || s[start] == ' ')
start++;
while (s[end] == '\n' || s[end] == '\t' || s[end] == ' ')
end--;
if (start == 0 && end == ft_strlen(s) - 1)
return ((char*)s);
if (end - start < 0)
return (NULL);
printf("%d\n", end - start);
p = (char*)malloc(sizeof(char) * (end + 1 - start));
index = 0;
while(start <= end)
{
p[index] = s[start];
index++;
start++;
}
p[index] = '\0';
return (p);
}
我想在end-start的值小于0时返回NULL。即使在调试函数后使用的printf中,该值是负数,该函数也不会返回NULL,并且在我编译代码时分段故障。
当我找到问题的答案时,我真的不知道该怎么办,这只是我的第二个问题。
我改变了条件
if (end < start)
return (NULL);
并用于end和start size_t类型,并知道它的工作原理。 非常感谢您的评论。
代码实际上是对前导和尾随空格进行了修剪 ,但是在许多情况下(包括所有空格)都具有UB。
while (s[end] == '\n' || s[end] == '\t' || s[end] == ' ')
end--;
上面的代码导致s出现不确定行为,因为end < 0
且s[end]
是不确定行为。
char *strtrim(char const *s) {
// First first non-white-space
while (isspace((unsigned char ) *s))
s++;
if (*s == 0) return NULL;
// Find last non-WS
const char *end = s;
const char *last_non_space = s;
while (*end) {
if (!isspace((unsigned char ) *end)) {
last_non_space = end;
}
end++;
}
// Allocate
size_t length = (size_t) (last_non_space - s + 1);
char *dest = malloc(length + 1);
if (dest == NULL) return NULL;
memcpy(dest, s, length);
dest[length] = '\0';
return dest;
}
也许代替return (p);
,则return p[index];
? 只是一个建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.