dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Dynamic Allocated String to std::string

  1. #1
    Join Date
    Jul 2017
    Posts
    78

    Dynamic Allocated String to std::string

    Code:
    std::string new_str = data;
    free(data);
    If data is a string with a null terminate character, will std::string copy all the characters from data?
    So am i safe to free the data pointer?

    Thank you.

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,511

    Re: Dynamic Allocated String to std::string

    Yes and yes.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.9.3)

  3. #3
    Join Date
    Jul 2017
    Posts
    78

    Re: Dynamic Allocated String to std::string

    Thank you!!!

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,262

    Re: Dynamic Allocated String to std::string

    Quote Originally Posted by babaliaris View Post
    So am i safe to free the data pointer?
    Yes, but only if you malloced it!
    Victor Nijegorodov

  5. #5
    Join Date
    Jul 2017
    Posts
    78

    Re: Dynamic Allocated String to std::string

    Quote Originally Posted by VictorN View Post
    Yes, but only if you malloced it!
    I used malloc.

  6. #6
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,119

    Re: Dynamic Allocated String to std::string

    Question is, why are you using malloc() and free()?
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)