004-tips

作者: 飞升之路 | 来源:发表于2019-08-04 22:37 被阅读0次

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

相关文章

  • 004-tips

    warning: address of stack memory associated with local va...

网友评论

      本文标题:004-tips

      本文链接:https://www.haomeiwen.com/subject/vosudctx.html