std::string as struct member variable

below is the problem !!!


Hi have this code

Expand|Select|Wrap|Line Numbers
  1. struct SF {
  2. std::string mnemonic;//mnemonic that represents it
  3. std::string name;//a descriptive name
  4. ushort num_val1;// number of the first value
  5. uchar possiblevalues_num; //number of the possible values.
  6. uchar type; /* = 1 if the feature is utilized in the models*/
  7. };
basically i am trying to declare a std::string object in a struct to later fill it with information

the next step i allocate an array of SF structs and try to do it

Expand|Select|Wrap|Line Numbers
  1. SF * FTab;
  2. FTab = (SF *) calloc(6, sizeof(SF));
  3. FTab[0].num_val1 = (ushort) 5;
  4. FTab[0].mnemonic("xpto");
the ushort type i can acess, the std::string generates a segmentation fault error, and i can't understant why. Does anyone know what i am doing wrong?

PS- sorry for the bad english.

Below is solution

E
M
M
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 6,292
#2: Oct 16 '07

re: std::string as struct member variable


It's the call to calloc.

C++ uses constructors and destructors to initialize and clean up objects. calloc doesn't know about this so never called them. Your string members are garbage.

Do not use C memory allocation in C++.

Use only new an delete. Here is the corrected code:

Expand|Select|Wrap|Line Numbers
  1. struct SF {
  2. std::string mnemonic;//mnemonic that represents it
  3. std::string name;//a descriptive name
  4. unsigned short num_val1;// number of the first value
  5. unsigned char possiblevalues_num; //number of the possible values.
  6. unsigned char type; /* = 1 if the feature is utilized in the models*/
  7. };
  8. int main()
  9. {
  10. SF * FTab;
  11. FTab = new SF[5];
  12. FTab[0].num_val1 = 5;
  13. FTab[0].mnemonic ="xpto";
  14. }
Decide now whether you will write in C++ or not. If yes, then do not:
1) malloc, calloc, alloc, etc.....
2) memcpy, mem... anything
3) free
4) exit(1)
5) strcpy, str... anything

for openers.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...