简体   繁体   中英

What is the issue with this static variable assignment to a pointer in local function?

int* func(int *ptr)
{
  static int a = 5;
  ptr = &a;
  return ptr;
}

Someone asked me this question in an interview. Now the point is, the variable 'a' is static, so, unlike ordinary variables which are declared, which loses it's value (popped from stack) once the function returns, this variable retains it's value as it is a static one.

Then i didn't understand, what's the issue with this piece of code?

There is no point in having ptr as a parameter. The passed value is not used. You could change this to

int* func()
{
  static int a = 5;
  return &a;
}

The value (address you're pointing to) of ptr that you are passing in is NOT changing outside the function as you are changing a locally scoped copy of ptr

It needs to be passed in by reference or pointer to pointer for it to change.

int* func(int **ptr)
{
  static int a = 5;
  *ptr = &a;
  return *ptr;
}

There is no issue. a is static so it exists through the lifetime of the execution. It is syntactically invisible outside func . You are just returning the address of some "hidden" global variable.

I'm bringing back your attention for local static variables. All time the variables will be remain same from last call. So, if you increase the variable a=a+1 then next time the value is remain 6. Here come how it happens. Each local declare new space in memory in each call. But in static variable you are telling to use same memory for every time. So, pointer will remain same. That why you are getting same address. This is not unexpected.

There isn't an issue, unless the caller doesn't understand what the function does. This is quite possible, given that people may assume the function modifies the value pointed to by the parameter.

For instance, if somebody writes code like

int foo = 0;
func(&foo);
assert(foo == 5);

They will have an issue.

The interviewer may have been looking for a solution like:

int *func(int *ptr) {
    static int a = 5;
    *ptr = a; //modify value being pointed to by argument
    return ptr;
}

There is a thread-safety issue: returning a non-constant pointer to a makes it possible that some thread will modify the value while another thread is reading it. Data races have undefined behavior.

I'll also toss in that returning a raw pointer is horrible practice, since I haven't seen it in the other answers. int& func() should be preferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM