Thread: Do I need to delete dynamic memory before leaving a function

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    If you're sure that the library won't require the abject later on, deleting it is fine.
    You could also use smart pointers...which will automatically destroy it when not needed.

  2. #2
    Registered User
    Join Date
    Feb 2010
    Posts
    17
    I just found out experimentally that if I try to delete it just before I leave the function, I get a segmentation fault. This fault happens after the last line of the function and before the first line the main after calling the function. It seems that I cannot delete it without problems but that would seem to contradict what i have read about dynamically allocated memory and deleting.

    @manasij7479 What is a smart pointer? How would you implement one?

  3. #3
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Quote Originally Posted by njitram2000 View Post
    I just found out experimentally that if I try to delete it just before I leave the function, I get a segmentation fault. This fault happens after the last line of the function and before the first line the main after calling the function. It seems that I cannot delete it without problems but that would seem to contradict what i have read about dynamically allocated memory and deleting.
    That just means that it is needed afterwards.
    @manasij7479 What is a smart pointer? How would you implement one?
    I've never implemented one...but a popular way is using reference counting.(Google the term)
    But unless you're sure that you can do better, stick with the ones provided by the C++ standard.
    Smart pointer - Wikipedia, the free encyclopedia

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Delete an element in a dynamic array?
    By beta3designs in forum C Programming
    Replies: 34
    Last Post: 08-22-2011, 03:34 AM
  2. Dynamic memory allocation for structs passed to function
    By eXcellion in forum C Programming
    Replies: 18
    Last Post: 03-30-2011, 03:30 PM
  3. Pointer/Dynamic Memory/function problem
    By Artist_of_dream in forum C++ Programming
    Replies: 17
    Last Post: 12-26-2004, 05:57 PM
  4. dynamic memory deletion via function
    By starkhorn in forum C++ Programming
    Replies: 4
    Last Post: 08-25-2004, 09:11 AM