Roola
Roola

Reputation: 137

dynamic allocation of array of struct pointers

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);
}

Upvotes: 0

Views: 946

Answers (2)

us2012
us2012

Reputation: 16263

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());
}

Upvotes: 1

user1773602
user1773602

Reputation:

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

Upvotes: 6

Related Questions