使用malloc,struct和char *堆积腐败

我的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的新手,因此可能会有一些我没有看到的明显事物。

非常感谢任何帮助,谢谢。

这是不正确的:

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

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

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

值得一读我是否投出了malloc的结果?