使用malloc,struct和char进行堆损坏* [英] Heap Corruption with malloc, struct and char *

查看:104
本文介绍了使用malloc,struct和char进行堆损坏*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C程序似乎内存损坏.我使用_ASSERTE( _CrtCheckMemory( ) );查找问题说明,并且该语句在其前面的一行上显示了scep_conf->engine_str = NULL;.因此,如果我理解正确,那之前的malloc发生了什么事,对吧?

I seem to have a memory corruption in my C program. I used _ASSERTE( _CrtCheckMemory( ) ); to find the problem statement and it breaks on a line that says scep_conf->engine_str = NULL; right before it. So if I understood it correctly, the malloc before that broke something, right?

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

So this is the part of the code that causes the issue:

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语言的新手,所以可能看不到某些明显的东西.

Basically I don't get why it would corrupt my memory here. I am new to C and so there may be something obvious I am not seeing.

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

Any help will be greatly appreciated, thank you.

推荐答案

这是错误的:

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

,因为它仅为SCEP_CONF*(而不是SCEP_CONF)分配足够的内存.应该是:

as it only allocates enough memory for a SCEP_CONF*, not a SCEP_CONF. it should be:

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

值得一读我是否强制转换malloc的结果?

这篇关于使用malloc,struct和char进行堆损坏*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆