-3

我一直在寻找这个问题的答案,但似乎找不到解决方案。当参数长度不同时,没有错误。当它们的长度相同时,会发生段错误。该函数旨在比较两个字符串并返回一个新字符串,其中包含每个第 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);
        }
    }

谢谢您的帮助!

4

2 回答 2

3

好吧,这可能与以下事实有关:当两个字符串的长度完全相同时,您的函数永远不会返回任何内容,因此结果是垃圾。然后将其解释为指针。而且……嗯……你知道接下来会发生什么,不是吗?

让我们适当地缩进该代码并添加一些注释,好吗?

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? */
}
于 2013-03-12T01:35:04.613 回答
1

有几个问题,尼克的回答指出了主要问题。另一个在这里:

result[lengthLarge + 1] = '\0'; // out of bounds! 
// this should be result[lengthLarge] = '\0'

此外,此签名更适合您的目的:

char* charMax(const char *string1, const char *string2);
于 2013-03-12T01:43:05.360 回答