char* returning question

This is a discussion on char* returning question within the C Programming forums, part of the General Programming Boards category; I have a few questions about functions returning char * : Here I have two programs, the green how the ...

  1. #1
    * Death to Visual Basic * Devil Panther's Avatar
    Join Date
    Aug 2001
    Posts
    768

    char* returning question

    I have a few questions about functions returning char *:

    Here I have two programs, the green how the program works without any problems:
    Code:
    
    char *func(void)
    {
       char *returnstr;
    
       returnstr = (char *) malloc(100);
    
       //  put something into the string
    
       return(returnstr);
    }
    
    int main()
    {
       char *str;
    
       str = func();
       printf("%s", str);
    
    // I think I need to free() the str,
    // but to free here something that was allocated 
    // inside func() looks kind of weird, and alittle stupid
    // so I'm not sure what do with the allocated memory...
    
       return(0);
    }
    
    And the red, the wrong way to return char *:
    Code:
    
    char *func(void)
    {
       char returnstr[100]={0};
    
       //  put something into the string
    
       return(returnstr);
    }
    
    int main()
    {
       printf("%s", func());
    
       return(0);
    }
    
    Can someone please explain to me what is the problem with the red code, and why do I have to work the way I did with in the green code?

    Thank you.
    "I don't suffer from insanity but enjoy every minute of it" - Edgar Allen Poe

    http://www.Bloodware.net - Developing free software for the community.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The array goes out of scope when the function ends. This effectively destroys whatever it contains. Or as far as you're concerned it's unable to be used any way. Just like you can't assign arrays with the = sign, you can't return them.

    But as to the issue, it's because the array goes out of scope and is destroyed.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    * Death to Visual Basic * Devil Panther's Avatar
    Join Date
    Aug 2001
    Posts
    768
    I see, but what about the allocated memory do I really need the free() tagging along with the function??? It looks kind of weird?

    Also, why can't I directly print to the screen the returned string (address)?
    "I don't suffer from insanity but enjoy every minute of it" - Edgar Allen Poe

    http://www.Bloodware.net - Developing free software for the community.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Yes. For every allocation, you need to free. Print what to the screen? The array's contents? Because it's already been destroyed.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    * Death to Visual Basic * Devil Panther's Avatar
    Join Date
    Aug 2001
    Posts
    768
    No, I meant if I want to place this in the green code:
    Code:
    printf("%s", func());
    "I don't suffer from insanity but enjoy every minute of it" - Edgar Allen Poe

    http://www.Bloodware.net - Developing free software for the community.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can, you'll just create a memory leak because you don't have a pointer to the string, so you can't free lit later.


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    char* foo()
    {
    	char a[] = "abc";
    	return a;
    }
    char* bar()
    {
    	char* a = malloc(4);
    	a = "abc";
    	free(a); // Needs this.
    	return a;
    }
    char* fine()
    {
    	return "abc";
    }
    
    
    
    int main()
    {
    	char* s;
    	printf("%s\n", foo());  // Err: Stack data goes out of scope
    	printf("%s\n", bar());  // Err: Heap data needs free'ing, no no
    	printf("%s\n", fine()); // Okay: In data section. Fine.
    	return 0;
    }
    If you need data, it's going to have to come from a safe place. What you could be doing, is passing a local pointer of main to a function (with preallocated memory on heap or stack) and then strcpy (not assign the pointer!) whatever stuff you generate in foo() or bar(), and then continue. Like this:

    Code:
    char* foobar(char* s)
    {
    	char a[] = "abc";
    	strcpy(s, a); // Not assigning s to a, strcpy'ing!
    	return s;
    }
    
    int main()
    {
    	char* s = malloc(64); // Needs allocation!
    	printf("%s", foobar(s));
    	return 0;
    }

  8. #8
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,163
    Don't forget:
    Code:
    char *also_fine(void)
    {
      static char a[] = "This is a string";
    
      return a;
    }
    Variables declared as static in a function are not allocated on the stack so the above function will work fine. It's not without its drawback too though.
    If you understand what you're doing, you're not learning anything.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,507
    char* a = malloc(4);
    a = "abc";
    free(a); // Needs this.
    This is wrong - you're not freeing what you malloc'ed, that was lost with your assignment.
    What you're freeing here is "abc".
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    ---
    Join Date
    May 2004
    Posts
    1,379
    Code:
    char* a = malloc(4);
    strcpy(a,"abc");
    free(a); // Needs this.
    Not sure if I understood what Salem was saying. Will that work? Was it becasue a was assigned a string literal?

  11. #11
    FOX
    Join Date
    May 2005
    Posts
    188
    Quote Originally Posted by sand_man
    Code:
    char* a = malloc(4);
    strcpy(a,"abc");
    free(a); // Needs this.
    Not sure if I understood what Salem was saying. Will that work? Was it becasue a was assigned a string literal?
    That will work. Salem's point before was that when you assigned the a pointer with a string literal, you lost memory location of the memory you allocated with malloc. Trying to free that now with a will fail, since a is now pointing to the string literal and not the allocated memory.

  12. #12
    * Death to Visual Basic * Devil Panther's Avatar
    Join Date
    Aug 2001
    Posts
    768
    Quote Originally Posted by Tonto
    If you need data, it's going to have to come from a safe place. What you could be doing, is passing a local pointer of main to a function (with preallocated memory on heap or stack) and then strcpy (not assign the pointer!) whatever stuff you generate in foo() or bar(), and then continue. Like this:

    Code:
    char* foobar(char* s)
    {
    	char a[] = "abc";
    	strcpy(s, a); // Not assigning s to a, strcpy'ing!
    	return s;
    }
    
    int main()
    {
    	char* s = malloc(64); // Needs allocation!
    	printf("%s", foobar(s));
    	return 0;
    }

    but basicly if I pass the s allocated string to the foobar function I don't need to return(s), since the string will be returned with all the changes inside the variable I just passed to it. In other words:
    Code:
    void foobar(char *s)
    {
       strcpy(s, "hello world");
      // no return
    }
    
    main()
    {
       char *s = (char *) malloc(100);
    
       foobar(s);
       printf("%s", s);
    }
    "I don't suffer from insanity but enjoy every minute of it" - Edgar Allen Poe

    http://www.Bloodware.net - Developing free software for the community.

  13. #13
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    Quote Originally Posted by Devil Panther
    but basicly if I pass the s allocated string to the foobar function I don't need to return(s), since the string will be returned with all the changes inside the variable I just passed to it. In other words:
    Code:
    void foobar(char *s)
    {
       strcpy(s, "hello world");
      // no return
    }
    
    main()
    {
       char *s = (char *) malloc(100);
    
       foobar(s);
       printf("%s", s);
    }
    It depends on what you want to do. Consider strcpy():

    Code:
    char *strcpy(char *dest, const char *src);
    Even though it returns a pointer, quite often you don't see it used. But there are times when a return value like that can be useful.

    Code:
    char *s = (char *) malloc(100);
    Why the cast to char?

  14. #14
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Quote Originally Posted by kermit
    Code:
    char *s = (char *) malloc(100);
    Why the cast to char?
    This cast is not needed in C. It is in C++.
    Kurt

  15. #15
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    >> but basicly if I pass the s allocated string to the foobar function I don't need to return(s), since the string will be returned with all the changes inside the variable I just passed to it. In other words

    Of course, but you seemed very keen on doing printf("%s", foobar()); or something And that was my bad with reassigning the a pointer, however sand_man's code is correct because the data is cpy'd to the allocated memory which is fine to free(). I had re-assigned it to point to "abc" which is illegal to free, pretty bad example in the first place.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. question about returning an array
    By Jasonymk in forum C++ Programming
    Replies: 6
    Last Post: 08-07-2003, 09:37 AM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21