Thread: Function returns string

  1. #16
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    So do you only want one string? Or do you need an array of strings?

    Your function has a memory leak. Count the malloc()'s and then count the free()'s.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  2. #17
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    >Pretty much . . . but what happens if the first call to malloc fails (formula==NULL)? Boom . . . segfault.

    Code:
    else{
       return 0;
    }
    ?


    >You're aware that declarations in the middle of a block is C++/C99 and not C89?
    I wasn't. To be honest I thought the formula = malloc(20 * sizeof *formula); line belonged to the declarations and that the whole malloc sequence (starting with if ( formula != NULL )) belonged to that line... which is - looking at it now - stupid.


    >Try running gdb from the command line. [edit] Like this: http://cboard.cprogramming.com/showp...79&postcount=7 [/edit]
    Afaik I don't have a command line function in DevC++ (I'm aware that this might be a very dumb answer). I'm looking into it now though, something with MinGW I think...

    Thanks so much for your help.
    Last edited by rkooij; 08-29-2006 at 09:18 AM.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  3. #18
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    >So do you only want one string? Or do you need an array of strings?
    Yes I only want one string.

    >Your function has a memory leak. Count the malloc()'s and then count the free()'s
    Oh, then I'm guessing free(string); in the main has no use?
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  4. #19
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Click on Start->All Programs->Accessories->Command Prompt (for windows xp). That will give you a command prompt.

    Once you have a command prompt open, you can use cd to change directories:
    Code:
    C:\Documents and Settings\User>cd ..
    
    C:\Documents and Settings>cd "User\My Documents"
    
    C:\Documents and Settings\User\My Documents>cd programs
    
    C:\Documents and Settings\User\My Documents\programs>
    Once you're in the same directory as your program's executable, you can debug it with gdb.
    Code:
    C:\Documents and Settings\User\My Documents\programs>gdb executable.exe
    Welcome to GDB ...
    (gdb) run
    program running . . .
    Segmentation fault
    (gdb) backtrace
    the location of the segfault...
    (gdb) list
    code listing...
    (gdb) quit
    The program is running. Exit anyway? y
    
    C:\Documents and Settings\User\My Documents\programs>
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #20
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by rkooij
    >So do you only want one string? Or do you need an array of strings?
    Yes I only want one string.
    Well, if you only want one string, you only need one malloc statement. Something like this:
    Code:
    char *full_name(char *first_name, char*lastname) {
        char *name = malloc(strlen(first_name) + strlen(lastname) + 1);
        if(!name) return 0;
    
        sprintf(name, "%s %s", first_name, last_name);
    
        return name;
    }
    
    void call_name(void) {
        char *name = full_name("John", "Smith");
    
        puts(name);
        free(name);
    }
    Output:
    Code:
    John Smith
    Your function has a memory leak. Count the malloc()'s and then count the free()'s
    Oh, then I'm guessing free(string); in the main has no use?
    Count your malloc statements. 1 + 20. Count your free statements. 1.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #21
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Well, if you only want one string, you only need one malloc statement. Something like this:
    > Hmmmmm ok!! So that's how malloc works, hehe.... excellent example, thank you very much!

    >Count your malloc statements. 1 + 20. Count your free statements. 1.
    I count only 1 malloc... ok ok that's after I changed the malloc request according to your tips above

    Damn how I wish there was a way to thank you guys other than just putting down the 6 letter word.

    I can't express how grateful I am, hope one day I can pay you back.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  7. #22
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    So what's the latest code - do you only have one malloc and one free?
    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.

  8. #23
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I count only 1 malloc
    Apparently.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #24
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Yes, according to dwks' example, only 1 malloc;

    Code:
    /************************ Floating point converter ****************************/
    //* Function:   converts a decimal value to a floating point
    //* Parameters: flt: decimal value to convert
    //* Returns:    formula: floating point (string)
    //*
    char* floating_point(float flt)
    {
       char hex[9], hex_2[9], temp[3], *p;
       char **formula;
       int decimal[4], i=0, ii=0;
       short cnt=0, cnt2=0;
    
       union
       {
          unsigned long i;
          float f;
       }v;
       
       formula = malloc(21);
       if (!formula)
       {
           return 0;
       }
    
       v.f = flt;
       sprintf(hex_2,"%08lx",v.i);
    //   puts(hex_2);
    
       cnt=7;
       while(cnt2<=3)
       {
          sprintf(temp,"%c%c",hex_2[cnt-1],hex_2[cnt]);
          printf("%s\t",temp);
          decimal[cnt2] = strtol(temp,&p,16);
          cnt-=2;
          cnt2++;
       }
       printf("\n");
       sprintf(*formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);
    //   puts(*formula);
    
       
       return *formula;
    }
    /******************************************************************************/
    Code:
             case '7':
                  
                  string = floating_point(0.012);
                  puts(string);
                  free(string);
                  
             break;
    Last edited by rkooij; 08-30-2006 at 01:34 AM.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  10. #25
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > char **formula;
    Should be char *formula;
    to match your return result

    > sprintf(*formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);
    Drop the *, you want to write the string to where the pointer points
    sprintf(formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);

    Ditto with the puts(formula)

    > return *formula;
    And here as well
    return formula;
    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.

  11. #26
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by Salem
    > char **formula;
    Should be char *formula;
    to match your return result

    > sprintf(*formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);
    Drop the *, you want to write the string to where the pointer points
    sprintf(formula,"%d\t%d\t%d\t%d",decimal[0],decimal[1],decimal[2],decimal[3]);

    Ditto with the puts(formula)

    > return *formula;
    And here as well
    return formula;
    Aren't

    > char **formula;
    Should be char *formula;
    to match your return result

    and

    > return *formula;
    And here as well
    return formula;

    contradictive?

    And I thought I couldn't return a string but had to return a pointer... as it looks from return formula; I'm returning a string now? Or does the asterisk in char* floating_point(float flt) cover that?
    Last edited by rkooij; 08-30-2006 at 06:25 AM.
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

  12. #27
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    contradictive?
    Nope. In one place you are delcaring a char* in the other you are using the variable that happens to be a char*

    the return type of your function is a char*

    int a;
    char* formula;

    a is an int
    formula is a char*

    so to return a char* you just return formula.

    As said, the same goes for sprintf and puts which expect a char*

    And I thought I couldn't return a string but had to return a pointer... as it looks from return formula; I'm returning a string now? Or does the asterisk in char* floating_point(float flt) cover that?
    formula is a pointer because that's how you declared it.
    The declaration char* formula; is what "covers" it
    Last edited by spydoor; 08-30-2006 at 07:27 AM.

  13. #28
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Basiclly, if you have a string like this,
    Code:
    char *str;
    When you want to use the string, use just plain str, such as for puts() calls or whatever. *str is the same as str[0], and so you should only use it when you want to access the first character in the string.

    Given the char*str above, if your function also returns a char*, then you can just use this
    Code:
    return str;
    because "str" is a char*. If you returned *str, it would be like returning a character, which isn't what the signature would indicate.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #29
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    That's great explanation guys, kind of what I already had in mind. Thank you both of you!
    http://www.f1rstracing.nl/
    OS: Windows XP
    Compiler: Dev-C++

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 05-19-2009, 08:17 AM
  2. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM
  3. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  4. Custom String Parsing Function
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-01-2002, 11:07 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM