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分配,有会导致堆栈溢出,最好,使用外部变量

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

原因-数组越界操作了

Bus error: 10 error

strcpy 数组不够装,操作忘记了 malloc(length+1)

其他

关于字符串指针经常用来变更的,建议使用malloc重新分配新变量,不用使用以及定义的一些字符串常量指针

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,752评论 0 38
  • 最全的iOS面试题及答案 iOS面试小贴士 ———————————————回答好下面的足够了-----------...
    zweic阅读 7,629评论 0 73
  • ———————————————回答好下面的足够了---------------------------------...
    恒爱DE问候阅读 5,718评论 0 4
  • __block和__weak修饰符的区别其实是挺明显的:1.__block不管是ARC还是MRC模式下都可以使用,...
    LZM轮回阅读 8,755评论 0 6
  • “每一个用心写作的人,都是一道美丽的风景。 ”——霖山《简友风采》 文/霖山 —1— 她出身于知识分子家庭,耳濡目...
    霖山阅读 5,863评论 35 50

友情链接更多精彩内容