0

Here my example code which works fine:

//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

No problem.

Now here my example with strange error:

// 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

It's seem the malloc function write/crush in the second pointer. I don't understand where is the problem in my code, it's very strange.

3
  • sizeof( structDeep2 )?? Commented May 9, 2018 at 13:56
  • Yes it's bad rewrite of example I corrected that for all "struct"malloc. Thx Commented May 9, 2018 at 13:58
  • You allocate the size for the struct not to the struct pointer. Commented May 9, 2018 at 14:29

1 Answer 1

2

When you do:

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

you allocate the size of a pointer, but you want to allocate a structure, so you must do:

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

Now (assuming malloc succeeds), you can safely do:

structDeep2->structDeep1->arrChar1 = malloc( sizeof(char ) * 2); 
Sign up to request clarification or add additional context in comments.

1 Comment

Don't worry, it won't be the last time that happens.... (and... do not assume malloc succeeds -- it has a return -- check it -- every time...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.