Странная ошибка в C с malloc указателя в указателе - PullRequest
0 голосов
/ 09 мая 2018

Вот мой пример кода, который работает нормально:

  //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Функция записи / дробления во втором указателе.Я не понимаю, где проблема в моем коде, это очень странно.

1 Ответ

0 голосов
/ 09 мая 2018

Когда вы делаете:

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

Вы выделяете размер указателя, но хотите выделить структуру, поэтому вы должны сделать:

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

Теперь (при условии, что malloc преуспевает), вы можете безопасно выполнить:

structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...