004-tips

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)致堆棧溢出,最好,使用外部變量

link

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重新分配新變量,不用使用以及定義的一些字符串常量指針

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容