简体   繁体   中英

LeetCode ERROR: AddressSanitizer: heap-buffer-overflow

My code can print the answer correctly, but when I try to return the ans variable, it shows heap-buffer-overflow.

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;
}

The error description is like:

==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)

You need to allocate one more byte for ans to make room for the \0 that should be at the end of the string:

    // ...

    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;
}

Copying can also be done simpler by using memcpy and don't forget to check that malloc succeeds:

    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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM