Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Pointer in C?

Tags:

c

pointers

global

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? */

}
like image 768
TonyGW Avatar asked Jun 20 '26 02:06

TonyGW


2 Answers

  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.

like image 149
Ed Heal Avatar answered Jun 22 '26 15:06

Ed Heal


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;
like image 36
Tim Avatar answered Jun 22 '26 15:06

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!