Thread: warning: function returns addresss of local variable

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    27

    warning: function returns addresss of local variable

    Code:
    #include <stdio.h>
    #include <string.h>
    
    char* test(char* s) {
      char ret[]="";
      strcpy(ret, s);
      return ret;
    }
    
    int main() {
      puts(test("hello"));
    }
    I get error:
    putstest.c: In function ‘test’:
    putstest.c:7:3: warning: function returns address of local variable

    Could someone explain what's gone wrong please. Thanks.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    It's a warning, not an error, and it says it all by itself.

    EDIT: Also, your code is subject to undefined behaviour, as you're writing to stack memory you haven't allocated and return a pointer to the array which has expired, as the warning says.
    Last edited by GReaper; 12-25-2011 at 04:22 PM.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    27
    Quote Originally Posted by GReaper View Post
    It's a warning, not an error, and it says it all by itself.
    Output gives blank line instead of "hello".

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Quote Originally Posted by gunitinug View Post
    Output gives blank line instead of "hello".
    As I said, "Undefined behaviour".
    Devoted my life to programming...

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    27
    Quote Originally Posted by GReaper View Post
    As I said, "Undefined behaviour".
    ok thanks

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by gunitinug View Post
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char* test(char* s) {
      char ret[]="";
      strcpy(ret, s);
      return ret;
    }
    
    int main() {
      puts(test("hello"));
    }
    I get error:
    putstest.c: In function ‘test’:
    putstest.c:7:3: warning: function returns address of local variable

    Could someone explain what's gone wrong please. Thanks.
    Simplest explanation.... C does not know how to return arrays from functions.
    It just plain can't do that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. warning: address of local variable ‘f’ returned
    By dayalsoap in forum C++ Programming
    Replies: 9
    Last Post: 07-20-2011, 10:51 PM
  2. Replies: 4
    Last Post: 07-11-2011, 10:50 AM
  3. Replies: 5
    Last Post: 08-14-2009, 03:15 AM
  4. Error - function returns address of local variable
    By tltying in forum C Programming
    Replies: 5
    Last Post: 05-28-2007, 02:26 AM
  5. Replies: 20
    Last Post: 11-12-2005, 03:10 PM