【问题标题】:C - Valgrind detects an error in my reverse-string functionC - Valgrind 在我的反向字符串函数中检测到错误
【发布时间】:2014-05-17 16:28:00
【问题描述】:

我编写了一个看起来运行良好的小程序,但是当我运行 memcheck 时,valgrind 给了我一个奇怪的错误。我需要帮助来解释错误代码:)

#include <stdio.h>
#include <stdlib.h>


int get_length(char* str){
   int i=0;
   char c = str[0];
   while(c!='\0'){
   i++;
   c=str[i]; 
   }
   return i;
}

char* rev(char* str){
   int length = get_length(str);
   char* x=malloc(length*sizeof(char));
   int i;
   length-=1;
   for(i=0; i<=length; i++){
      x[i]=str[length-i];
   }
   return x;
}

int main(){
   char* s=rev("roma");
   printf("%s\n",s);
   free(s);
}

valgrind 输出如下:

Invalid read of size 1
==14727==    at 0x4C29724: __GI_strlen (mc_replace_strmem.c:405)
==14727==    by 0x4E9907A: puts (ioputs.c:37)
==14727==    by 0x400673: main (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727==  Address 0x51ba044 is 0 bytes after a block of size 4 alloc'd
==14727==    at 0x4C28D84: malloc (vg_replace_malloc.c:291)
==14727==    by 0x400601: rev (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727==    by 0x400663: main (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727== 
amor
==14727== 
==14727== HEAP SUMMARY:
==14727==     in use at exit: 0 bytes in 0 blocks
==14727==   total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==14727== 
==14727== All heap blocks were freed -- no leaks are possible

我还注意到,如果我使用 calloc() 而不是 malloc(),valgrind 根本不会检测到任何错误。

注意:我写 get_length() 函数只是为了好玩,哈哈

【问题讨论】:

    标签: c malloc valgrind reverse memcheck


    【解决方案1】:

    你分配的字符比你需要的少:

    char* x=malloc(length*sizeof(char));
    

    应该是

    char* x=malloc(length+1);
    

    乘以sizeof(char) 是不必要的,因为标准要求它是1。添加1 是必需的,因为您需要一个额外的字符作为空终止符,而您的函数无法添加该字符。这就是printf 尝试打印字符串时发生无效读取的原因。

    要解决此问题,请分配length+1,并在从函数返回x 之前添加x[length] = '\0';

    【讨论】:

      猜你喜欢
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2020-04-17
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多