1

If a variable is created on the stack, it will get deleted when the function in which it is created exits. So presumably a pointer to such a variable cannot be returned from the function and nor can it be passed to another thread (unless you're certain the other thread won't use it after the function in which it was created exits.)

Is it legitimate to pass a pointer to a location on the stack as an argument to another function, if it's part of the api contract of the other function that it will do everything with that pointer in the same thread?

This is not quite the same; the pointer is being used after the original function ends.

Community
  • 1
  • 1
George Simms
  • 3,930
  • 4
  • 21
  • 35
  • 3
    You should try to ask one *clear* question at a time. – juanchopanza Nov 01 '14 at 13:11
  • As juancho said, the stackoverflow part is a completely different question. Focus on the lifetime of automatic variables and pointers bit. – Ben Voigt Nov 01 '14 at 13:11
  • Edited accordingly. [http://en.wikipedia.org/wiki/Stack_overflow](Wikipedia) suggests stack overflow is likely to cause a segfault, but it's not clear if that is true in all cases or only in the case of infinite recursion. – George Simms Nov 01 '14 at 13:15

2 Answers2

3

Is it legitimate to pass a pointer to a location on the stack as an argument to another function, if it's part of the api contract of the other function that it will do everything with that pointer in the same thread?

Yes - It is still on the stack and therefore exists

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
2

C knows nothing about stacks.

The lifetime of an automatic variable is until it goes out of scope. The scope can be smaller than the entire function where it is declared. That object can be used while it is alive, from any function and any thread that has a valid pointer to it... but when you start talking about threads, you must also protect against race conditions, which happen when multiple threads simultaneously access the same memory location (and at least one of the accesses is a write).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720