warning: address of stack memory associated with local variable 'rs' returned [-Wreturn-stack-address]
char * findCommonPrefix(char *s1, char *s2)
{
int len = strlen(s1);
char result[len];
int count = 0;
for( ;*s1 != '\0' && *s2 != '\0' && *s1 == *s2; s1++,s2++)
{
result[count] = *s1;
count++;
}
if (count > 0)
{
result[count] = '\0';
char *rs = (char *)malloc(count+1);
strcpy(rs, result);
return rs;
}
return "";
}
原因-使用了堆棧上的本地變量返回,如果此處改為malloc分配,有會(huì)導(dǎo)致堆棧溢出,最好,使用外部變量
void findCommonPrefix(char *s1, char *s2, char *totalRs)
{
int len = strlen(s1);
if (len == 0 ) {
strcpy(totalRs , "");
return ;
}
char result[len + 1];
int count = 0;
for( ;*s1 != '\0' && *s2 != '\0' && *s1 == *s2; s1++,s2++)
{
result[count] = *s1;
count++;
}
if (count > 0)
{
result[count] = '\0';
printf("count %d, rs %s \n", count, result);
strcpy(totalRs, result);
printf("count %d, totalrs %s \n", count, totalRs);
return ;
}
strcpy(totalRs , "");
}
Abort trap 6 error in C
原因-數(shù)組越界操作了
Bus error: 10 error
strcpy 數(shù)組不夠裝,操作忘記了 malloc(length+1)
其他
關(guān)于字符串指針經(jīng)常用來(lái)變更的,建議使用malloc重新分配新變量,不用使用以及定義的一些字符串常量指針