1

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)
1
  • Dont forget to allocate one more extra byte to mark as end of the string Commented Jan 25, 2023 at 14:02

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.