2

I'm learning C and i'm trying to do the following:

  • create a structure table from a function
  • return pointer to the newly created table

typedef of table: typedef char table [8][8];

So, I created this function:

table* create_table() {
  table o;
  return &o;
}

But i get an error from compiler saying that I'm returning address of a local variable.

How do I do t o create a table from the function and then return the pointer.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
helloc
  • 23
  • 2

2 Answers2

8

You cannot give back the address of a local variable, as the address become invalid one the function (create_table) returns, instead, you should create it on the heap:

table* create_table() 
{
    table * o;
    o = malloc(sizeof(table));
    // Edit - added initialization if allocation succeeded.
    if (o != NULL)
    {
        memset(o, 0, sizeof(table));
    }
    return o;
}
MByD
  • 135,866
  • 28
  • 264
  • 277
  • 2
    ... and you should document in the comment at the top of your `create_table` function (you do have a comment there, right :-) that (a) the function may return NULL if it's unable to allocate memory, and (b) the caller of the function is responsible for calling `free` on the returned `table` when it's no longer needed. – David Gelhar May 15 '12 at 13:42
  • ... and you should check for a `NULL` return from `malloc` before attempting to fill in the new table's fields. – Fred Foo May 15 '12 at 13:50
  • @larsmans I doubt this will help, the app will be on a death row – Ulterior May 15 '12 at 14:03
  • 1
    @Ulterior: I'm not sure what you mean. – Fred Foo May 15 '12 at 14:04
  • @larsmans http://stackoverflow.com/questions/6637906/resource-acquisition-failure-handling – Ulterior May 15 '12 at 14:06
  • 1
    @Ulterior - such (no-)handling will result in undefined behavior. not that recommended... – MByD May 15 '12 at 14:09
  • @Ulterior: there are lots of applications where out of memory can reasonably be handled. E.g., an interactive program for handling big datasets, where the user doesn't want to see their command history and settings wiped just because they tried to load a file that's too big to handle in one go. – Fred Foo May 15 '12 at 14:12
2

You can't return the address of a local variable. It is deallocted when the function exits. You have to allocate it using malloc and return that pointer. For example:

table* ptr = malloc(sizeof(table));
memset(ptr, 0, sizeof(table));
return table;
sashang
  • 11,704
  • 6
  • 44
  • 58