char * as an out pramater
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: char * as an out pramater

  1. #1
    Join Date
    Sep 2003
    Posts
    815

    char * as an out pramater

    I need to send a char * as an out parameter

    I have the function

    BuildString(char * myNewString)
    {

    //build here the myNewString using std:string and then cast to char *

    }

    I don't know the size of the string when I'm calling the function, this is why I use char * and not char x[MAX_SIZE]
    Also the out value must be char * and not std:string
    I'm using std:string inside the function for convinice

    anyway my quetion is:
    how do I define this char * before calling the function
    I can't just define it char *myNewString
    so I used "char *myNewString = NULL"

    Is that legal?

  2. #2
    Join Date
    Feb 2003
    Location
    Brazil
    Posts
    296
    Try realloc

    I gess realloc can solve your problem:

    Each time you know what you´ll add on your char * realloc the memory with it´s size plus the new size i.e:

    Code:
    ...
    #include "stdlib.h"
    #include "string.h"
    
    int main()
    {
      char * teste; 
      char add[11];
    
      teste = (char *)malloc(6);
    
      strcpy(&add[0]," world !!!");
    
      strcpy(teste,"hello");
    
      realloc(teste,sizeof(teste) + sizeof(&add));
    
      strcat(teste,&add[0]);
     
      printf("%s\n",teste);
    }

  3. #3
    Join Date
    Aug 2003
    Location
    Greece
    Posts
    206
    My personal opinion is that the piece of code which has performed an allocation should also be responsible for de-allocation.

    So, I suggest your function looks like:

    Code:
    void    BuildString (char* str, unsigned long size, unsigned long* ret)
    {
    
    }
    And the arguments are:

    - str : Pointer to a preallocated memory area which will receive the string.
    - size : Size of the provided memory area expressed in characters.
    - ret : Pointer to an integer that will receive the required size of 'str' in order the output string to fit completely (along witht the null termination).

    The function should copy as many as possible data to the provided str buffer. If upon return the *ret is smaller than size than you have success, otherwise allocate *ret and call function again.

    Note that calling the function with size = 0, will return in *ret the required size str.

    Usage:

    Code:
    // 16 chars should be enoung for most
    // common cases.
    
    char str[16];
    unsigned long ret;
    
    BuildString(str, sizeof(str), &ret);
    
    if (ret <= sizeof(str))
    {
        // Well done
    }
    else
    {
        char* str = new char[ret];
    
        BuildString(str, ret, 0);
    
        // No way to fail - remember to delete
        // str.
    
    }
    Of course there are many other approaches as well, each one having its pros and cons.

    Regards,

    --harizak

  4. #4
    Join Date
    Sep 2003
    Posts
    815
    harizak

    my xase is not common, the string length is unknown and could be 1000 or even more, so I have to allocate inside the function
    and release it after the function finishes....

  5. #5
    Join Date
    Apr 1999
    Posts
    27,444

    Re: char * as an out pramater

    Originally posted by avi123
    I need to send a char * as an out parameter
    Not if you send the pointer to the char*. See code below:
    Code:
    #inclue <cstring>
    
    void BuildString(char **myNewString)
    {
         //...
         *myNewString = new char [10000]; // or whatever
         strcpy(*MyNewString, "abc123");
    }
    
    int main()
    {
         char *MyString;
         BuildString( &MyString );
         // now MyString contains the new string "abc123"
         delete [] MyString;
    }
    The problem with this code (as others have pointed out) is that the function that the deallocation of the string should be done by the function (or class) that allocated the string. Otherwise, the code above should work correctly.

    Regards,

    Paul McKenzie

  6. #6
    Join Date
    Sep 2003
    Posts
    815
    Paul

    Does it matter if I send char * or pointer to char *?
    I mean what's wrong with this code:

    #inclue <cstring>

    void BuildString(char *myNewString)
    {
    //...
    myNewString = new char [10000]; // or whatever
    strcpy(MyNewString, "abc123");
    }

    int main()
    {
    char *MyString;
    BuildString( MyString );
    // now MyString contains the new string "abc123"
    delete [] MyString;
    }
    --------------------------------------------------------------------------------

  7. #7
    Join Date
    Sep 2002
    Location
    Singapore
    Posts
    673
    Pointer to Pointer and Reference to Pointer
    Explains the reason behind using pointer-to-pointer and reference-to-pointer to modify a pointer passed to a function.

  8. #8
    Join Date
    Aug 2003
    Location
    Greece
    Posts
    206
    NOTE: Allocating memory within a function and having the caller de-allocate it later is asking for trouble. If the function that performs the allocation is in a dll, and the caller is a function within an exe or other dll, runtime heap incompatibilities may be raised. This depends on the runtime library you link each module with making sometimes different heaps to be used for alloc / free.

    Regards,

    --harizak

  9. #9
    Join Date
    Sep 2003
    Posts
    815
    well I can use std:string so the code will be:

    #inclue <string>

    void BuildString(string &str
    {
    //string manipulation here

    }

    int main()
    {
    string myStr;
    BuildString(MyString);
    }

    my question where does myStr is deallocated?

  10. #10
    Join Date
    Sep 2003
    Location
    Forever Gone... For Now...
    Posts
    1,515
    myStr in "deallocated" when it does out of scope - just like any other automatic variable.
    Thought for the day/week/month/year:
    Windows System Error 4006:
    Replication with a nonconfigured partner is not allowed.

  11. #11
    Join Date
    Jul 2001
    Location
    Netherlands
    Posts
    751
    Vicodin:"myStr in "deallocated" when it does out of scope - just like any other automatic variable"

    **** no. It is passed in by reference and will get changed by reference and never leave scope.

  12. #12
    Join Date
    Sep 2003
    Location
    Forever Gone... For Now...
    Posts
    1,515
    **** no. It is passed in by reference and will get changed by reference and never leave scope.
    fransn: No.

    The code was:
    Code:
    string myStr; 
    BuildString(MyString);
    myStr is not a reference. It is a variable of type string. See MSDN "Declarators and Variable Declarations".

    never leave scope.
    _Everything_ goes out of scope at some point...
    Thought for the day/week/month/year:
    Windows System Error 4006:
    Replication with a nonconfigured partner is not allowed.

  13. #13
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,471
    Yeah, but the whole point about using string (and vector and deque, etc.) is that you don't have to worry about memory allocation and deallocation: the classes take care of it.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  14. #14
    Join Date
    Jul 2001
    Location
    Netherlands
    Posts
    751
    Vicondin:"The code was:

    code:--------------------------------------------------------------------------------
    string myStr;
    BuildString(MyString);

    "
    Yes but that's not the code I'm talking about. See the & there in the function declaration?

    void BuildString(string &str)
    {

    }

  15. #15
    Join Date
    Dec 2002
    Posts
    47
    rabelo wrote:
    #include "stdlib.h"
    #include "string.h"

    int main()
    {
    char * teste;
    char add[11];

    teste = (char *)malloc(6);
    strcpy(&add[0]," world !!!");
    strcpy(teste,"hello");
    realloc(teste,sizeof(teste) + sizeof(&add));
    strcat(teste,&add[0]);
    printf("%s\n",teste);
    }
    rabelo: this is bad form - sizeof(teste) != 6 !!

    hirazak's suggestion is okay - the Windows API (GetWindowText) does exactly this.

    avi123 - the suggestions to use char ** and have the caller free the memory looks good for C programs. Passing an STL string by reference is great for C++ if the STL library is available - not all platforms have it.

    If you use the char ** approach, you will need to document whether the caller must use free() or delete[] to reclaim the memory. Some runtime libraries don't like mixing malloc() with delete or new with free().

    frasn - never say "never"! (just kidding)

    -rick

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center