C 我不知道';我不明白为什么我会犯这个错误

C 我不知道';我不明白为什么我会犯这个错误,c,memory,valgrind,C,Memory,Valgrind,我得到了以下代码: /* main.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> int main (){ int i; char *msg = "This is a simple and small message"; int len = strlen (msg); char *new_msg = (char *) malloc (len); for (

我得到了以下代码:

/* main.c */

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

int main (){
  int i;
  char *msg = "This is a simple and small message";
  int len = strlen (msg);
  char *new_msg = (char *) malloc (len);
  for (i = 0; i < len; i++)
    new_msg[i] = 'A';
  printf ("%s\n", new_msg);
  free (new_msg);
  return 0;
}
我得到了这个输出的结果:

==8286== Memcheck, a memory error detector
==8286== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8286== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==8286== Command: ./main
==8286== 
==8286== Invalid read of size 1
==8286==    at 0x4C2C1B4: strlen (vg_replace_strmem.c:412)
==8286==    by 0x4EA09FB: puts (ioputs.c:36)
==8286==    by 0x400636: main (main.c:12)
==8286==  Address 0x51de062 is 0 bytes after a block of size 34 alloc'd
==8286==    at 0x4C28C20: malloc (vg_replace_malloc.c:296)
==8286==    by 0x400601: main (main.c:9)
==8286== 
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
==8286== 
==8286== HEAP SUMMARY:
==8286==     in use at exit: 0 bytes in 0 blocks
==8286==   total heap usage: 1 allocs, 1 frees, 34 bytes allocated
==8286== 
==8286== All heap blocks were freed -- no leaks are possible
==8286== 
==8286== For counts of detected and suppressed errors, rerun with: -v
==8286== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
我看到所有分配的内存都被释放了,但是我仍然得到一个我不理解的错误


感谢您的帮助。

这是一个非常简单的错误:对
new\u msg
的读取无效,因为没有空终止符

您已将
char
s的数量分配为原始字符串的长度,因此当前没有空间来容纳
'\0'
,而不会产生未定义的行为。按以下方式更改代码以修复此问题:

char *new_msg = malloc (len+1);
for (i = 0; i < len; i++)
    new_msg[i] = 'A';
new_msg[len] = '\0';
char*new_msg=malloc(len+1);
对于(i=0;i
您的代码中有许多内容需要更改

1)
len
应该是
size\u t
而不是
int
,因为
strlen()
返回类型为
size\u t

2)
(char*)malloc(len)放下演员阵容。这不是一个错误,尽管有一些不应该抛出的原因

3)
new\u msg
不是以NULL结尾的
\0
。这就是发生错误的原因。

您使用
strlen()
获取长度,但不包含“\0”。

因此,当您malloc一个新数组时,应该使用
len+1
,并将
new\u msg[len]
设置为
'\0'

数字1和2不是此问题的原因。提到它们没关系,但请明确区分。@Haris演员阵容不是错误,而是非常有用的信息,一方面可以防止不正确的分配。另一方面,首先,谢谢你的解释。现在它起作用了。其次,我看到你移除了malloc的演员阵容。为什么呢?我在有演员和没有演员的情况下运行它,仍然得到相同的输出(即使在valgrind上)。有什么不同吗?@mik。不强制转换背后的想法是,您已经指定了类型,因此再次重复同一段代码。演员阵容也可以隐藏细微的错误。
char *new_msg = malloc (len+1);
for (i = 0; i < len; i++)
    new_msg[i] = 'A';
new_msg[len] = '\0';