design - C - Advantages of dynamically allocating a single struct -


i have been browsing c code , noticed people write functions dynamically allocate , initialise c structs, e.g.

struct pool {     /* ... */ };  struct pool *pool_new(/* ... */) {      struct pool *p = calloc(1, sizeof(*p));      /* initialise p ... */      return p; } 

i unsure if practice kind of definition enforces use of dynamic allocation , may lead unnecessary memory fragmentation. know way define opaque objects i've seen kind of code "normal" structs well. advantages of kind of practice?

one reason dynamic on static allocation portability of object. stack-allocated object can passed down stack pointer, never up, while heap-allocated pointer can passed around @ will.

the stack smaller heap, if structures take lot of ram, can better heap allocate them.

using allocation function allows ensure fields filled in correctly, important if fields calculated other values in structure , don't want have duplicate calculations everywhere.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -