-2

I can't quite figure out how to do this, I've tried this and several variations and some will compile and seemingly work ok but I'll get very random segfaults and it has something to do with the way I'm declaring these structs. All the info in the structs are dynamic. Please let me know the proper way to do this, thank you.

#include <stdio.h>
#include <stdlib.h>


typedef struct 
{
    char* s2string1;
    char* s2string2;
    int   s2int1;
} struct2;


typedef struct 
{
    char*    s1string1;
    char*    s1string2;
    struct struct2* mystruct;
    int      int1;    
} struct1;


struct struct2* RetS2(char* CopyMe)
{
    int* Array = (int*) malloc (sizeof (int) * 5);
    Array[0] = strlen (CopyMe);

    struct struct2* S2 = (struct struct2*) malloc ( sizeof (struct2) );

    S2->s2int1 = Array[0];

    return S2;

}


struct struct1* RetS1()
{
     struct struct1* S1 = (struct struct1*) malloc ( sizeof (struct1) );

     struct struct2* S2 = RetS2();

     S1->mystruct = S2;

     S1->int1 = S2->S2int1; 


     return S1;
}

int main()
{

    struct struct1 Top = RetS1();

    if (Top->mystruct->s2int1 == 10)
        // do something

    return 0;
}
soqu49
  • 1

1 Answers1

1

Your code has multiple issues:

  1. This is the main issue:

    RetS2's function definition is

    struct struct2* RetS2(char* CopyMe)
    

    which means that it expects a char* as its first argument. But when you call it:

    struct struct2* S2 = RetS2();
    

    you don't pass an arguments. This invokes Undefined Behavior.

  2. Here:

    int* Array = (int*) malloc (sizeof (int) * 5);
    

    You allocate memory for 5 ints. You use the first element of the array and stops using it. You also forgot the free the allocated memory for Array.

  3. The cast in malloc (and family) is not required in C.
  4. You don't free the malloced memory for S2 and S1.
Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • Thanks cool guy, but I fixed everything and still get the crash. Can someone give me a simple yes/no answer if I'm declaring the memory for structs properly? That is all I'm asking. – soqu49 Oct 04 '15 at 12:01
  • You still get the crash? What did you change `struct struct2* S2 = RetS2();` to? And the memory allocation is correct. But see issue #2 in my answer. Also, you should check the result of `malloc` to see if it was successful and should also `free` the allocated memory(See issue #4) – Spikatrix Oct 04 '15 at 12:06
  • Yes I know about free but free'ing the memory is not the issue here. Anyways thanks it must be something else. – soqu49 Oct 04 '15 at 12:08
  • Yes. It is. Again, What did you change `struct struct2* S2 = RetS2();` to? – Spikatrix Oct 04 '15 at 12:09