6

Is it safe to pass a pointer to a static struct to a function?

I have something like this:

mymodule.c:

static MYEVENT_STRUC_T event;
uint_32 _myRtos_set_event(MYEVENT_STRUCT_T* event_ptr, uint_32 mask);

uint_32 mymodule_set_event(uint_32 event_mask){   

    /* Kernel function */
    /* Defined outside mymodule.c,*/
    /* Is it safe to call it with &event?  */
    return _myRtos_set_event(&event, event_mask);

}
2
  • A priori, it seems safe. Note: you forgot the input parameter MYEVENT_STRUCT_T* event_ptr in your definition, therefore _myRtos_set_event(event, event_mask); Commented Mar 14, 2014 at 14:39
  • The vast majority of functions that don't deal with memory allocation will be happy with an address of a static variable. You cannot call realloc or free and pass a pointer to a static variable to it, for example, but most functions are safe. Commented Mar 14, 2014 at 14:44

1 Answer 1

16

It is safe. static doesn't mean "can't be used outside the module", but rather "can't be referenced outside the module", i.e. the symbol itself won't be exported, but the variable still exists somewhere in the memory of the process an can be used between modules as well.

The only thing I'm uncertain of is that I'm not sure it's safe to pass data from user-mode to kernel-mode via pointer, if that's what you're doing. If I recall correctly, there is some function you're supposed to call that copies memory from user-space to kernel-space. Not entirely sure, though.

Sign up to request clarification or add additional context in comments.

2 Comments

"there is some function you're supposed to call that copies memory from user-space to kernel-space" --- the kernel takes care of this; unless you are writing the kernel, you should not even know such a function exists.
If this is Windows, I believe kernel mode code can touch user mode memory, if your kernel mode code is executing in the context of user's process. That is user mode code calls kernel mode code, and that kernel mode code executes in the user's context and can hence have access to user-mode memory up until the kernel mode code completes executing and returns from the user's call. I'm not quite sure how it works for Linux. And my information is back from NT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.