【问题标题】:Heap Corruption with malloc, struct and char *使用 malloc、struct 和 char 的堆损坏 *
【发布时间】:2012-07-24 21:37:53
【问题描述】:

我的 C 程序中似乎有内存损坏。我用_ASSERTE( _CrtCheckMemory( ) ); 来查找问题陈述,它在前面写着scep_conf->engine_str = NULL; 的那一行中断了。所以如果我理解正确的话,之前的 malloc 会破坏一些东西,对吧?

所以这是导致问题的代码部分:

scep_conf = (SCEP_CONF *) malloc(sizeof(scep_conf));
scep_conf->engine = (struct scep_engine_conf_st *) malloc(sizeof(struct scep_engine_conf_st));
scep_conf->engine_str = NULL;

标题中的定义:

typedef struct {
    struct scep_engine_conf_st *engine;
    char *engine_str;
} SCEP_CONF;

struct scep_engine_conf_st{
    char *engine_id;
    char *new_key_location;
    int storelocation; 
    char *dynamic_path;
    char *module_path; 
    int engine_usage;
};

SCEP_CONF *scep_conf;

基本上我不明白为什么它会破坏我的记忆。我是 C 新手,所以可能有一些我没有看到的明显内容。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: c memory malloc heap-memory heap-corruption


    【解决方案1】:

    这是不正确的:

    scep_conf = (SCEP_CONF *) malloc(sizeof(scep_conf)); 
    

    因为它只为SCEP_CONF* 分配足够的内存,而不是SCEP_CONF。应该是:

    scep_conf = malloc(sizeof(*scep_conf)); /* cast unnecessary. */
    

    值得一读Do I cast the result of malloc?

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2020-08-02
      • 2020-01-15
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多