Freeing memory

This is a discussion on Freeing memory within the C++ Programming forums, part of the General Programming Boards category; Should I free 'buf' after assigning a dynamic char vector to it? I cannot decide: Code: vector<char> vec(dynamic size,'1'); char ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    816

    Freeing memory

    Should I free 'buf' after assigning a dynamic char vector to it?

    I cannot decide:
    Code:
    vector<char> vec(dynamic size,'1');
    
    char * buf = &vec.at(0);
    
    free (buf);
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    255
    No. The memory you're pointing your buf pointer at was allocated by the std::vector object. std::vector was written to do its own memory management and thus will clean up after itself. Besides, in C++ if you have to allocate memory from the free store, you generally want to use new / new [] and delete / delete [] instead of malloc and free.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    816
    Great, thank you!
    Compiler MSVC++ 2013 with Code::Blocks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic memory and realloc(), freeing memory
    By C_Sparky in forum C Programming
    Replies: 6
    Last Post: 10-06-2010, 08:55 PM
  2. Freeing memory
    By vbdave78 in forum C Programming
    Replies: 7
    Last Post: 11-18-2009, 12:56 PM
  3. Freeing memory
    By bikr692002 in forum C++ Programming
    Replies: 6
    Last Post: 04-09-2006, 05:58 PM
  4. Freeing memory necessary?
    By Snip in forum C Programming
    Replies: 3
    Last Post: 11-05-2005, 07:01 AM
  5. freeing memory
    By mart_man00 in forum C Programming
    Replies: 1
    Last Post: 04-27-2003, 09:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21