using malloc to create array of strings does not seem to return proper pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MorgaG
    New Member
    • Sep 2008
    • 1

    using malloc to create array of strings does not seem to return proper pointer

    Hello all. First time posting. I am using something similar to the following code:

    const int hbas = somefunctioncal l();
    string * ptr = (string*)malloc (hbas*sizeof(st ring));
    ptr[0] = "hello world";

    I am using VS 2008 on a XP machine. When I watch all the variables and step through the calls malloc seems to have a legit hex pointer but once malloc returns, ptr has <Bad Ptr> for a value.

    Any thoughts or tips would be greatly appreciated!

    Thanks!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    string is a class, by mallocing memory to it in that manor you fail to call the constructor and so the class is not initialised. At this point I would imagine attempting to use it is likely to produce undefined behaviour.

    NEVER use malloc to allocate memory for a class use new which will call the constructor. In fact in general don't use malloc in C++ use new.

    Thus your code becomes

    const int hbas = somefunctioncal l();
    string * ptr = new string[hbas];
    ptr[0] = "hello world";

    However why do this and manage the memory yourself when you could use a vector and have the memory managed automatically for you

    const int hbas = somefunctioncal l();
    vector<string> strarray(hbas);
    strarray[0] = "hello world";

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      And while we are on the subject of allocating memory for an object, may I ask why a string*?

      Do you believe that a variable length string is on the stack where it's length has to be known at compile time? Maybe the string is already on the heap?

      At least one implementation I have seen has a 15 byte array and a char* on the stack. That is, strings that fit in the array don't need dynamic allocation. This means greater speed. When the string is longer than 15, the 15 bytes are copied to a heap array and the 15 byte array becomes disused.

      So you see the string is already on the heap. By allocating a string* you force the allocating of the 15 byte array and the char* at run-time thereby removing a speed enhancing feature of string.

      Have you looked at your implementation of basic_string? What do you see there?

      Comment

      Working...