Thread: pointer functions - nebie question

  1. #1
    Registered User
    Join Date
    Mar 2006

    pointer functions - nebie question

    Hi all
    say I have this function:
    char *trim(char *string)

    If I understand it correctly the function's result value has to be allocated, let's say, by malloc. But how is this allocation going to be freed? All I do in my program is this:

    string = trim(string)

    Thanks in advance

    Here is the function
    char *
    trim (char *string)
      char *result = 0;
      /* Ignore NULL pointers.  */
      if (string)
          char *ptr = string;
          /* Skip leading whitespace.  */
          while (strchr (WHITESPACE_STR, *ptr))
          /* Make a copy of the remainder.  */                     
          if ((result = (char *) malloc(strlen(ptr)+1)) == NULL)   
            fprintf(stderr,"trim() - Cannot allocate; %s",ptr);    
            return NULL;                                           
          /* Move to the last character of the copy.  */
          for (ptr = result; *ptr; ++ptr)
            /* NOWORK */;
          /* Remove trailing whitespace.  */
          for (--ptr; strchr (WHITESPACE_STR, *ptr); --ptr)
              *ptr = '\0';
      return result;

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    The calling function would have to free() the memory. Alternatively, you could pass a buffer to your trim() function in which the trimmed string is stored. Or, if you're not concerned with keeping a pure copy of the string you could just hack up the original string in the function.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Umeň, Sweden

  4. #4
    Registered User
    Join Date
    Mar 2006
    I guess it wouldn't be a good design for the calling function to free memory that was allocated in the called function. Since the trimmed value could not be bigger than the *string parameter, I will free the allocated memory in the trim function itself and copy the result value back to the string parameter.

    Thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 01:19 AM
  2. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  3. Function pointer question
    By sbayeta in forum C Programming
    Replies: 9
    Last Post: 08-06-2004, 08:15 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 05:58 PM