相关疑难解决方法(0)

为什么我不应该对未由malloc()分配的变量调用free()?

我在某个地方读到free用来摆脱不是通过调用创建的对象是灾难性的,这是malloc真的吗?为什么?

c memory malloc free memory-management

9
推荐指数
4
解决办法
6913
查看次数

读取内存无效 - valgrind

这是我的代码:我正在尝试获取结构的信息并深入复制信息.但是,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的报告

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)

c valgrind

8
推荐指数
1
解决办法
2385
查看次数

标签 统计

c ×2

free ×1

malloc ×1

memory ×1

memory-management ×1

valgrind ×1