LeetCode错误:地址消毒剂:堆缓冲区溢出

pgvzfuti  于 2023-01-29  发布在  其他
关注(0)|答案(1)|浏览(161)

我的代码可以正确地打印答案,但是当我试图返回ans变量时,它显示堆缓冲区溢出。

char * longestPalindrome(char * s){
    int le = strlen(s);
    int t = 0, it = 0;
    int start = 0, end = 0;
    int max = 0; 
    for (int i = 0; i < le; i++){
        it = i;
        for (int j = le-1; j > i; j--){
            t = 0;
            while (s[it] == s[j]){
                t++;
                j--;
                it++;
                if (j < i){
                    break;
                }
            }
            if (max < t){
                max = t;
                start = i;
                end = it-1;
            }
            it = i;
        }
    }
    char *ans;
    ans = (char *)malloc(sizeof(char)*(max));
    for(int i = 0; i < max; i++){
        ans[i] = s[start+i];
    }
    return ans;
}

错误描述如下所示:

==34==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000033 at pc 0x557f4a2709ab bp 0x7fff8135edd0 sp 0x7fff8135edc0
READ of size 1 at 0x602000000033 thread T0
    #2 0x7f4879d2e0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x602000000033 is located 0 bytes to the right of 3-byte region [0x602000000030,0x602000000033)
allocated by thread T0 here:
    #0 0x7f487a973bc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)
    #3 0x7f4879d2e0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
zzlelutf

zzlelutf1#

您需要为ans再分配一个字节,以便为应该位于字符串末尾的\0腾出空间:

// ...

    char *ans = malloc(max + 1);   // one extra byte

    for(int i = 0; i < max; i++){
        ans[i] = s[start+i];
    }
    ans[max] = '\0';               // and remember to terminate the string

    return ans;
}

使用memcpy也可以更简单地完成复制,不要忘记检查malloc是否成功:

char *ans = malloc(max + 1);

    if (ans) {                        // check that malloc succeeded
        memcpy(ans, s + start, max);  // instead of the loop
        ans[max] = '\0';
    }

    return ans;
}

相关问题