1

I have a double link list that stores some information. When I try and return one of the values inside the link list, I get the warning: function returns address of local variable.

This is my return statement:

return curr_val->value;

value is of type const void*.

Method signature is like: void *get_val(int key)

curr_val is of a struct type. It is equal to one of my nodes in the linked list.

how do I return the value and it not disappear after I return? BTW, I can not change the method signature.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
user972276
  • 2,973
  • 9
  • 33
  • 46
  • 1
    What is the method signature? What is `curr_val`? – Seth Carnegie Jan 26 '12 at 02:52
  • 1
    Edit your question to show us the function definition. – Keith Thompson Jan 26 '12 at 02:59
  • 1
    You haven't added enough info, but @Borealid is probably correct. Also +1 for heeding a copmiler warning. – Seth Carnegie Jan 26 '12 at 03:00
  • You should probably edit the question to add the code of the function so that we can work out why the compiler is warning you. But, as Seth said, you get good marks from us for paying attention to the compiler warnings. Anything the compiler bothers to warn about is probably a problem; they struggle to avoid giving false positives because that would undermine the usefulness of the warnings. – Jonathan Leffler Jan 26 '12 at 03:23
  • Duplicate: http://stackoverflow.com/questions/8743411/return-address-of-local-variable-in-c – Robert Groves Jan 26 '12 at 03:25

1 Answers1

2

The problem is likely that you have assigned the address of a stack-allocated variable to value. You need to use new or malloc to get memory for variables you intend to have continue to exist beyond the current stack frame.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • I also have a set_val(int key, const void* value) method. There I am just setting "curr_val->value = value;". Is that where I should be using malloc? If so, how can I use malloc and still get it equal to the value passed in? – user972276 Jan 26 '12 at 03:03
  • @user972276: If you're passing it in, the problem is where it's being gotten by whoever is calling `set_val`. – Borealid Jan 26 '12 at 03:04
  • `new` is not going to help for a `C` question. – Pascal Cuoq Jan 26 '12 at 03:16
  • @Complicatedseebio: oops, didn't look at the tags. I mentioned `malloc` anyhow, though. – Borealid Jan 26 '12 at 03:17