Thread: Freeing memory

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

    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);
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    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
    930
    Great, thank you!
    Using Windows 10 with Code Blocks and MingW.

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, 07: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, 04: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, 08:51 PM