c - return a static structure in a function -


c89 gcc (gcc) 4.7.2

hello,

i maintaining someones software , found function returns address of static structure. should ok static indicate global address of structure available until program terminates.

driver_api(driver_t*) driver_instance_get(void) {     static struct tag_driver driver = {     /* elements initialized here */     };      return &driver; } 

used this:

driver_t *driver = null; driver = driver_instance_get(); 

the driver variable used throughout program until terminates.

some questions:

  1. is practice this?
  2. is there difference declaring static outside function @ file level?
  3. why not pass memory pool function , allocate memory structure structure declared on heap?

many suggestions,

  1. generally, no. makes function non-reentrable. can used restraint in situations when code author knows doing.

  2. declaring outside pollute file-level namespace struct object's name. since direct access the object not needed anywhere else, makes more sense declare inside function. there's no other difference.

  3. allocate on heap? performance suffer. memory fragmentation occur. , caller burdened task of explicitly freeing memory. forcing user use dynamic memory when can avoided not practice.

    a better idea reentrable implementation pass pointer destination struct outside. way caller has full freedom of allocating recipient memory in way see fit.


of course, see here can c implementation of singleton-like idiom (and is, judging function's name). means function supposed return same pointer every time, i.e. callers supposed see , share same struct object through returned pointer. and, possibly, thy might expect modify same object (assuming no concurrency). in case see here function-wrapped implementation of global variable. so, changing here in case defeat purpose.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -