What are the benefits and drawbacks of making a function that returns a pointer to a static global variable from another object file?

Advertisements

I am thinking of doing this because it suits my compartmentalization ideas, so I am trying to figure out if it is a good idea performance-wise.

// obj1.c
static char *data;

char* return_pointer_for_data() {
    return data;
}

// obj2.c
static char *buffer;

void copy_data_to_buffer(char* ptr) {
    buffer[5] = ptr[5];
}

// main.c
copy_data_to_buffer(return_pointer_for_data());

I would like to know the benefits and drawbacks of doing return_pointer_for_data(), and how common this approach is. The other approach I am thinking of is:

// obj2.c
void copy_data_to_buffer(char* ptr1, char* ptr2) {
    ptr1[5] = ptr2[5];
}  

// main.c
char *data;
char *buffer;
copy_data_to_buffer(buffer, data);

I have gotten answers about access speed comparison for copying data, ranging from "it highly depends" to "it doesn’t matter", so I decided to base my decision on the benefits and drawbacks of return_pointer_for_data().

>Solution :

Benefits:

  1. Easy to share data over functions, you don’t have to pass a char* every time you call a function.

Drawbacks:

  1. If your program has multiple threads, it might result a race condition because multiple threads can write to it at the same time. You have to use a lock to protect it.
  2. It can make your code hard to maintain when it grows. You need to careful order your function calls because they might need other function to set up the global variable.

Performance does not matter too much in this case, the first approach has an overhead of a function call.

Leave a Reply Cancel reply