C字符串,strlen的和Valgrind的 [英] C strings, strlen and Valgrind

查看:126
本文介绍了C字符串,strlen的和Valgrind的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么Valgrind是吐出:

I'm trying to understand why Valgrind is spitting out :

==3409== Invalid read of size 8
==3409==    at 0x4EA3B92: __GI_strlen (strlen.S:31)

每当我在一个动态分配的字符串strlen的申请?

whenever I'm applying strlen on a dynamically allocated string?

下面是一个简短的测试用例:

Here is a short testcase :

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

int main() {

  char *hello = "Hello World";
  char *hello2;

  /* Step 1 */
  printf("Step 1\n");
  printf("strlen : %lu\n",(unsigned long)strlen(hello));

  /* Step 2 */
  hello2 = calloc(12,sizeof(char));
  hello2[0] = 'H';
  hello2[1] = 'e';
  hello2[2] = 'l';
  hello2[3] = 'l';
  hello2[4] = 'o';
  hello2[5] = ' ';
  hello2[6] = 'W';
  hello2[7] = 'o';
  hello2[8] = 'r';
  hello2[9] = 'l';
  hello2[10] = 'd';
  hello2[11] = 0;  

  printf("Step 2\n");
  printf("strlen : %lu\n",(unsigned long)strlen(hello2));
  free(hello2);

  return 0;
}

这是从Valgrind的输出结果:

And here is the result output from Valgrind :

lenain@perseus:~/work/leaf$ valgrind ./leaf
==3409== Memcheck, a memory error detector
==3409== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==3409== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info
==3409== Command: ./leaf
==3409== 
Step 1
strlen : 11
Step 2
==3409== Invalid read of size 8
==3409==    at 0x4EA3B92: __GI_strlen (strlen.S:31)
==3409==    by 0x40098A: main (in /home/lenain/work/leaf/leaf)
==3409==  Address 0x5189048 is 8 bytes inside a block of size 12 alloc'd
==3409==    at 0x4C234CB: calloc (vg_replace_malloc.c:418)
==3409==    by 0x4008F0: main (in /home/lenain/work/leaf/leaf)
==3409== 
strlen : 11
==3409== 
==3409== HEAP SUMMARY:
==3409==     in use at exit: 0 bytes in 0 blocks
==3409==   total heap usage: 1 allocs, 1 frees, 12 bytes allocated
==3409== 
==3409== All heap blocks were freed -- no leaks are possible
==3409== 
==3409== For counts of detected and suppressed errors, rerun with: -v
==3409== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

什么是避免这些警告的正确方法?难道他们的真正的警告?

推荐答案

这是最有可能与此相关的bug报告:

This is most likely related to this bugreport:

<一个href=\"https://bugzilla.redhat.com/show_bug.cgi?id=518247\">https://bugzilla.redhat.com/show_bug.cgi?id=518247

由于保罗已经建议,strlen的()在英特尔平台上可​​选择使用SSE优化,​​加快strlen的朋友。这加快涉及安全读取分配的块的背后,一些老版本的valgrind的还不明白。因此,升级你的valgrind,你会好起来的。

As Paul already suggested, strlen() on intel platforms optionally uses SSE optimization to speed up strlen and friends. This speed up involve safe reads behind the allocated blocks, something older versions of valgrind did not understand yet. So upgrade your valgrind and you will be OK.

这篇关于C字符串,strlen的和Valgrind的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆