Thread: Is there a memory leakage in this simple code snippet

  1. #31
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by medievalelks View Post
    Here's a version that doesn't depend on strdup or the POSIX call:

    Code:
    std::string dirname(const std::string & path)
    {
        std::string dir = path.substr(0, path.find_last_of("/"));
    
        return ((dir != path) ? dir : std::string("."));
    }
    Although that wouldn't work on a system that has different directory separators than '/', e.g a Windows system which uses : and \, or one of them systems that uses : only.

    But the idea is good, and it's definitely simple.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  2. #32
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Here's a more portable version:

    Code:
    std::string dirname(const std::string & path, const std::string & sep)
    {
        std::string dir = path.substr(0, path.find_last_of(sep));
    
        return ((dir != path) ? dir : std::string("."));
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  3. Memory leak by simple char
    By Ktulu in forum C++ Programming
    Replies: 42
    Last Post: 11-05-2006, 01:59 PM
  4. Replies: 14
    Last Post: 11-23-2005, 08:53 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM