0
votes

I am trying to dynamically allocate an array of struct in another struct here is the code segment

I don't get any syntax errors but I get segmentation fault once I try to enter str1

could someone explain why is there a segmentation fault, and what happens in memory in the dynamic allocation in such situation

struct A {
   string str1;
   string str2;
}

struct B {
   int count;
   A* A_array;
}


void GetB (B** b)
{

 *b = (B*) malloc(1*sizeof(B));
 cout << "Enter count";
 cin >> (**b).count;
 (**b).A_array = (A*) malloc((**b).count*sizeof(A));
 cout << "Enter str1";
 cin >> (**b).A_array[0].str1;
 cout << "Enter str2";
 cin >> (**b).A_array[0].str2;

}

int main(){
   B* b;
   GetB(&b);
}
2
what a horrible mix of C and C++ - user1773602
Is there a reason why you're using malloc instead of new? Generally, if you're programming in C++, you want to actually use C++. - Cornstalks
Start by deciding whether you're you're writing C or C++. If you're writing C, don't use cin or cout and don't cast the return from malloc. If you're writing C++, don't use malloc at all, and use std::vector instead of your home-rolled imitation. - Jerry Coffin
sorry about that I am using c++ but I my problem is with the malloc so I thought people with c or cpp experience can help with it that is why I but both on the tags - Roola
I'll repeat: if you're using C++, don't use malloc. When writing C++, it's best to forget that it exists at all. - Jerry Coffin

2 Answers

6
votes

The reason you are getting a crash is because string str1; string str2; do not get constructed properly.

And they are not constructed properly because malloc only allocates memory and doesn't call the constructors.

Which is what operator new is for in C++.

Therefore, as highlighted in comments:

  1. Never ever use malloc to allocate non-POD objects.
  2. Even better, never use malloc in c++ at all.
  3. And better still, never ever use manually allocated arrays, use std::vector instead
1
votes

Expanding on my comments, this would be an equivalent of your current program using some more idiomatic C++. I have deliberately kept the structure as close to your original as possible, but there are of course other issues to think about, like whether your classes should have constructors or private members.

struct A {
   string str1;
   string str2;
};

struct B {
   int count;
   vector<A> A_vec;
};

B GetB ()
{
   B myB;
   cout << "Enter count";
   cin >> myB.count;
   A a;
   cout << "Enter str1";
   cin >> a.str1;
   cout << "Enter str2";
   cin >> a.str2;
   myB.A_vec.push_back(a);
   return myB;
}

int main(){
   B b(GetB());
}