繁体   English   中英

C 中的奇怪错误,指针中的指针 malloc

[英]Strange error in C with a malloc of pointer in a pointer

这里我的示例代码工作正常:

//define struct
struct myStruct {
   char     *arrChar1;
   char     *arrChar2;
}
// code in Main
struct myStruct *structDeep1 = malloc( sizeof( struct myStruct *) );
structDeep1->arrChar1 = NULL;
structDeep1->arrChar2 = NULL;
structDeep1->arrChar1 = malloc( sizeof(char ) * 2); //2 char

if( structDeep1->arrChar1 == NULL)  puts("trace error");
else                                    puts("trace ok")
//stdout -> trace OK

没问题。

现在这里我的例子有奇怪的错误:

// define a second struct
struct myStructDeep2{
    struct myStruct     *structDeep1;
}
// next code in Main
struct myStructDeep2 structDeep2 = malloc( sizeof( struct myStructDeep2*) );
structDeep2->structDeep1 = malloc( sizeof( struct myStruct *) );
structDeep2->structDeep1->arrChar1 = NULL;
structDeep2->structDeep1->arrChar2 = NULL;
structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2); //2 char

if( structDeep2->structDeep1->arrChar1 == NULL)     puts("trace error");
else                                            puts("trace ok")
//stdout -> trace error

似乎 malloc 函数在第二个指针中写入/粉碎。 我不明白我的代码哪里出了问题,很奇怪。

当你这样做时:

structDeep2->structDeep1 = malloc( sizeof( struct myStruct *) );

你分配了一个指针的大小,但你想分配一个结构,所以你必须这样做:

structDeep2->structDeep1 = malloc( sizeof( struct myStruct) );

现在(假设 malloc 成功),您可以安全地执行以下操作:

structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM