Am i overusing malloc in c? -


i working on learning c. understand malloc() allocates block of bytes cannot changed or corrupted without user request, find myself using often. exact, using malloc every time want create either struct or of contents want reference in future. understand free() allocated memory when complete.

is use of malloc correct?

dynamic memory allocation (malloc , family) there 2 reasons:

  • your data needs persist beyond scope allocated (e.g. multithreading)
  • whatever allocating large stack

you should avoiding allocate dynamic memory other reason. automatic (stack) variables far less prone errors , automatically deallocated @ end of scope.

having "corrupted memory" call can arise bad programming , can happen on both stack , heap , should not rely on dynamic memory provide safety buffer overflows or other mistakes lead memory corruption.

there reason why many functions in c standard library pointer buffer argument put results in: allows allocate buffers on stack. e.g:

 ssize_t read(int fd, void *buf, size_t count); 

also mentioned answer: stack memory in cpu cache , far faster accessible.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -