小编Len*_*ain的帖子

C字符串,strlen和Valgrind

我试图理解为什么Valgrind正在吐痰:

==3409== Invalid read of size 8
==3409==    at 0x4EA3B92: __GI_strlen (strlen.S:31)
Run Code Online (Sandbox Code Playgroud)

每当我在动态分配的字符串上应用strlen时?

这是一个简短的测试用例:

#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] = …
Run Code Online (Sandbox Code Playgroud)

c string valgrind strlen

7
推荐指数
1
解决办法
5633
查看次数

标签 统计

c ×1

string ×1

strlen ×1

valgrind ×1