Thread: Trim function, possible leaks?

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    121

    Trim function, possible leaks?

    Hello, I am interested if that trim function is OK to be used, with no leaks possible.
    Code:
    static void trim(char* data)
    {
        char* begin= data;
        char* end = &data[aux_strlen(data)-1];
        while(*begin == ' ') {
            begin++;
        }
    
        while(*begin != '\0') {
    
            *data++ = *begin++;
        }
    
        while(*end == ' ') {
            *end-- = 0;
        }
    
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Since you don't call malloc or free, there is nothing to leak.

    FWIW, I think you need to do the end-- loop before doing the copy.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    505
    If you test it on a string which consists of all spaces I believe it will fail.

    To fix it, add the terminating nul on your second pass. Then calculate end
    and do the third and final pass.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Critique my trim function
    By atac in forum C Programming
    Replies: 4
    Last Post: 11-17-2013, 03:59 PM
  2. [C] trim function serious implementation
    By triceps in forum C Programming
    Replies: 10
    Last Post: 09-12-2011, 04:18 PM
  3. trim function - could you explain please
    By c_lady in forum C Programming
    Replies: 17
    Last Post: 03-27-2010, 09:19 AM
  4. Replies: 9
    Last Post: 04-21-2004, 01:52 PM
  5. trim string function (code)
    By ipe in forum C Programming
    Replies: 9
    Last Post: 01-06-2003, 12:28 AM

Tags for this Thread