我一直在寻找这个问题的答案,我似乎无法找到解决方案。当参数长度不同时,没有错误。当它们具有相同的长度时,会发生段错误。该函数用于比较两个字符串并返回一个包含每个第i个字符中最大字符串的新字符串。我的功能如下:
char* charMax(char* string1, char* string2)
{
int length1 = strlen(string1);
printf("%d", length1);
int length2 = strlen(string2);
int lengthLarge = length1 >= length2 ? length1 : length2;
int lengthSmall = length1 <= length2 ? length1 : length2;
char* largerString = length1 >= length2 ? string1 : string2;
char* result = malloc(lengthLarge + 1);
for (int i = 0; i < lengthSmall; i++)
result[i] = string1[i] > string2[i] ? string1[i] : string2[i];
if (length1 != length2)
{
for (int i = lengthSmall; i < lengthLarge; i++)
result[i] = largerString[i];
result[lengthLarge + 1] = '\0';
return result;
free(result);
}
}
感谢您的帮助!
答案 0 :(得分:3)
好吧,它可能与以下事实有关:当两个字符串具有完全相同的长度时,您的函数永远不会返回任何内容,因此它的结果是 garbage 。然后将其解释为指针。而且......嗯......你知道接下来会发生什么,不是吗?
让我们正确缩进该代码并添加一些评论,是吗?
char* charMax(char* string1, char* string2) {
int length1 = strlen(string1);
printf("%d", length1);
int length2 = strlen(string2);
int lengthLarge = length1 >= length2 ? length1 : length2;
int lengthSmall = length1 <= length2 ? length1 : length2;
char* largerString = length1 >= length2 ? string1 : string2;
char* result = malloc(lengthLarge + 1);
for (int i = 0; i < lengthSmall; i++) {
result[i] = string1[i] > string2[i] ? string1[i] : string2[i];
}
if (length1 != length2) {
for (int i = lengthSmall; i < lengthLarge; i++) {
result[i] = largerString[i];
}
result[lengthLarge + 1] = '\0';
return result;
free(result); /* uhm, what? this will never execute */
}
/* oops - what happens now? who knows? */
}
答案 1 :(得分:1)
有几个问题,Nik的答案指出了主要问题。另一个在这里:
result[lengthLarge + 1] = '\0'; // out of bounds!
// this should be result[lengthLarge] = '\0'
此外,此签名更适合您的目的:
char* charMax(const char *string1, const char *string2);