Global Pointer in C?

泄露秘密 提交于 2019-12-23 04:07:29

问题


I know a pointer is usually assigned upon its declaration, but I wondering if there's any way to create a global pointer in C. For example my code below: is it a good practice?

static int *number_args = NULL;

void pro_init(int number)
{
    number_args = &number;   /* initialize the pointer value -- is this okay? */

}

回答1:


  1. Avoid globals - They are a bad idea and usually lead into problems.
  2. You are taking an address of a variable on the stack. That will get reused somewhere down the line and hence having unintended results.

If you feel the need (why?) to have a global pointer then initialise if off the heap.




回答2:


That is valid. There are many good reasons to have global variables, especially static global variables. But if something doesn't need to be global, it's better to not make it global.

Also keep in mind that if more than one thread accesses that variable, you'll need to protect it somehow, probably with a mutex, or you may have race conditions.

Also, keep in mind that "number" is a stack variable. Arguments to functions and local variables are both allocated on the stack, and cease to exist outside of their scope. So unless "pro_init()" either never returns, or sets the variable back to NULL before it returns, you'll end up with an invalid pointer.

You might use heap memory instead, for example:

number_args = malloc(sizeof(int));
if (number_args == NULL) { /* handle malloc error */ }
*number_args = number;


来源:https://stackoverflow.com/questions/22005260/global-pointer-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!