我的代码可以正确地打印答案,但是当我试图返回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)
1条答案
按热度按时间zzlelutf1#
您需要为
ans
再分配一个字节,以便为应该位于字符串末尾的\0
腾出空间:使用
memcpy
也可以更简单地完成复制,不要忘记检查malloc
是否成功: