0

I was trying to define structure having an int and string type members.

typedef struct emp{
    int sno;
    string name;
}

When I allocated space using malloc and modified the name variable, it gives Segmentation Fault.
I searched on stackoverflow and found solution to use char* instead of string type. Is it because char* has a fixed size (pointer size)? Also how does sizeof treats a string variable since its length is not known before allocation?

dragosht
  • 3,237
  • 2
  • 23
  • 32
  • 3
    What is `string`? Are you sure that it is C and not C++? – Revolver_Ocelot Feb 24 '16 at 17:22
  • I think you must be confusing with C syntax in C++.. Use c compiler for c code. This will throw compilation error itself. – Sridhar Nagarajan Feb 24 '16 at 17:31
  • sorry ..its c++ ..compiled using g++ not gcc and no compile error was there.. – Abhishek Tiwari Feb 24 '16 at 17:41
  • If so, then you shouldn't be using malloc() to allocate space for objects. Use new() instead. – tofro Feb 24 '16 at 17:43
  • why..what's wrong with malloc..?? – Abhishek Tiwari Feb 24 '16 at 17:45
  • It does not actually create objects, only allocates memory. – Revolver_Ocelot Feb 24 '16 at 17:47
  • malloc()/free() is the way C allocates and frees memory. new/delete is how C++ does it, and it handles all of the necessary things that have to be done if what you're allocating/freeing is an object (i.e., calling the object's constructor/destructor functions). (BTW, new and delete are not functions; they work the same way as a return statement---no parens necessary.) – RobH Feb 24 '16 at 17:49
  • @RobH `new-expression` does more than just allocates memory. You can use `malloc` with C++ object, but you will need to handle all that extra stuff yourself. – Revolver_Ocelot Feb 24 '16 at 17:51
  • thank you for explanation..@RobH and @Revolver_Ocelot ...I understood..:) – Abhishek Tiwari Feb 24 '16 at 17:57
  • @Revolver_Ocelot That's pretty much what I said in my comment. new/delete allocates/frees memory and does the necessary object stuff, such as calling the constructor/destructor. – RobH Feb 24 '16 at 17:57
  • A std::string is a container ... and you do not know how it is implemented, and it might be implemented differently on different systems. On ubuntu 15.10 (64 bit), g++ 5.2.1, for example, sizeof(emptyString) reports 32 bytes, which does not change when you add characters. I infer from this that the characters are stored somewhere else. Then you can conclude that std::string contains pointers to where the data resides, and thus malloc (and free) won't know how to handle this split of location. – 2785528 Feb 24 '16 at 18:22

0 Answers0