Thread: How to partially free() memory

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    110

    How to partially free() memory

    This function takes a pointer to pointer argument, or, a pointer to a character string and does two things:
    1) Returns the first character of this string
    2) Makes the pointer point to the next character

    This means next time it is called, it always returns the next character.

    Code:
    char getToken(char **inputString){
        char returnCharacter = **inputString;
        *inputString = *inputString + 1;    //How do we fix this memory leak???
        return returnCharacter;
    }
    The problem? In this functions caller, input string has been malloc()'ed.

    If I understand correctly, every time I shift the pointer in getToken, Im losing reference to Heap memory and therefore lose any way to free it in future. How can I free it in this function?

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    Just save a copy of the original pointer in the caller. BTW. the function looks pretty useless, exactly the kind of thing that makes a program more complicated (yet another function) while adding no real benefit.

  3. #3
    Registered User
    Join Date
    Mar 2016
    Posts
    110
    Really? This function is critical in my programme. The caller handles a string and needs to iterate through the tokens. It needs to "pop" a character out every time it calls it. Any ideas on how to make it better?

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    Well, your function is essentially equivalent to:
    Code:
    char c = *p++;
    So why is it a function?

  5. #5
    Registered User
    Join Date
    Mar 2016
    Posts
    110
    Hmmmm, good point. I guess initially it probably did more things then I refactored it to just do what I mentioned in the OP. But now that I think about it, I could just do that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 12-28-2012, 04:07 PM
  2. How does free() know how much memory it has to free?
    By shiroaisu in forum C Programming
    Replies: 14
    Last Post: 09-09-2011, 11:28 AM
  3. partially summation
    By joerg in forum C Programming
    Replies: 0
    Last Post: 11-23-2007, 10:47 AM
  4. partially checking a string against a dictionary
    By axon in forum C++ Programming
    Replies: 2
    Last Post: 03-11-2003, 06:16 PM

Tags for this Thread