我在某个地方读到free用来摆脱不是通过调用创建的对象是灾难性的,这是malloc真的吗?为什么?
这是我的代码:我正在尝试获取结构的信息并深入复制信息.但是,valgrind显示"无效阅读".我知道那是我读过发布的内存.我不知道为什么; 有人能够为我解决这个问题吗?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char *name;
int age;
};
void get_info(struct student *dest, struct student *src)
{
memcpy(dest,src,sizeof(struct student));
dest->name = strdup(src->name);
}
int main()
{
struct student foo;
foo.id = 1001;
foo.name = strdup("kevin");
foo.age = 18;
struct student bar;
get_info(&bar, &foo);
puts(bar.name);
free(foo.name);
free(bar.name);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
valgrind --tool=memcheck --leak-check=full ./test
==2130== Memcheck, a memory error detector
==2130== Copyright (C) 2002-2013, and GNU GPL'd, by …Run Code Online (Sandbox Code Playgroud)