gpt4 book ai didi

c - 我不明白为什么我会收到这个 valgrind 错误

转载 作者:行者123 更新时间:2023-12-05 01:26:22 25 4
gpt4 key购买 nike

我得到以下代码:

/* 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;
}

我编译它,然后使用 valgrind 和以下命令运行它:
valgrind --leak-check=full --show-reachable=yes ./main

我得到了这个输出:
==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_msg 的读取无效。因为空终止符不存在。

您已分配的号码char s 等于原始字符串的长度,因此目前没有空间可以容纳 '\0'没有做出未定义的行为。更改您的代码如下以解决问题:

char *new_msg = malloc (len+1);
for (i = 0; i < len; i++)
new_msg[i] = 'A';
new_msg[len] = '\0';

关于c - 我不明白为什么我会收到这个 valgrind 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com