malloc in main() or malloc in another function: allocating memory for a struct and its members Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Allocating memory for a matrix with a single mallocPointers for struct and `for`Allocating memory and releasing the sameEdge cases for simulated malloc functiongetline substitute that will enforce 'n' as limit of characters readAllocating a contiguous block of memory for an arrayA pointer that stores its size at the frontDeletion of Word from Ternary Search Tree where Both Siblings PresentObject pool for allocating generic objects in aligned memorymalloc() and free() for Linux with system calls

Flight departed from the gate 5 min before scheduled departure time. Refund options

Is there public access to the Meteor Crater in Arizona?

Caught masturbating at work

How much damage would a cupful of neutron star matter do to the Earth?

Putting class ranking in CV, but against dept guidelines

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

My mentor says to set image to Fine instead of RAW — how is this different from JPG?

I can't produce songs

White walkers, cemeteries and wights

Special flights

Resize vertical bars (absolute-value symbols)

What is the role of と after a noun when it doesn't appear to count or list anything?

The Nth Gryphon Number

As a dual citizen, my US passport will expire one day after traveling to the US. Will this work?

How do living politicians protect their readily obtainable signatures from misuse?

Why is the change of basis formula counter-intuitive? [See details]

Proof by mathematical induction with the problem 40(2n)! ≥ 30^n

Can you force honesty by using the Speak with Dead and Zone of Truth spells together?

Asymptotics question

Google .dev domain strangely redirects to https

Did pre-Columbian Americans know the spherical shape of the Earth?

Tips to organize LaTeX presentations for a semester

Should a wizard buy fine inks every time he want to copy spells into his spellbook?

Is openssl rand command cryptographically secure?



malloc in main() or malloc in another function: allocating memory for a struct and its members



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Allocating memory for a matrix with a single mallocPointers for struct and `for`Allocating memory and releasing the sameEdge cases for simulated malloc functiongetline substitute that will enforce 'n' as limit of characters readAllocating a contiguous block of memory for an arrayA pointer that stores its size at the frontDeletion of Word from Ternary Search Tree where Both Siblings PresentObject pool for allocating generic objects in aligned memorymalloc() and free() for Linux with system calls



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned:



#include <stdio.h>
#include "buffer.h"

int main(int argc, char *argv[])

struct Buffer *tx_buffer = Buffer_create(8);

Buffer_destroy(tx_buffer);

return 0;



And this one shows how all memory allocations can be done within the main function:



#include <stdio.h>
#include "buffer.h"

int main(int argc, char *argv[])

uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
Buffer2_create(rx_buffer, ptr_rx_buffer, 8);

Buffer2_destroy(rx_buffer);

return 0;



And here are the contents of the header file buffer.h:



#ifndef _buffer_h
#define _buffer_h

#include <stdint.h>
#include <stdlib.h>

struct Buffer
uint8_t *buffer;
size_t size;
;

struct Buffer *Buffer_create(size_t size);

void Buffer_destroy(struct Buffer *who);

void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);

void Buffer2_destroy(struct Buffer *who);

#endif


And buffer.c:



#include <stdint.h>
#include <assert.h>
#include <stdlib.h>
#include "buffer.h"

struct Buffer *Buffer_create(size_t size)

struct Buffer *who = malloc(sizeof(struct Buffer));
assert(who != NULL);

who->buffer = malloc(sizeof(uint8_t)*size);
who->size = size;

return who;


void Buffer_destroy(struct Buffer *who)

assert(who != NULL);
free(who->buffer);
free(who);


void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)

assert(who != NULL);

who->buffer = buffer;
who->size = size;


void Buffer2_destroy(struct Buffer *who)

assert(who != NULL);
free(who->buffer);
free(who);



The Result



Both approaches work and the executable files for both end up being the same size.



My Question



Will either of these approaches result in memory leaks or poor performance?










share|improve this question









New contributor




David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    1












    $begingroup$


    When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned:



    #include <stdio.h>
    #include "buffer.h"

    int main(int argc, char *argv[])

    struct Buffer *tx_buffer = Buffer_create(8);

    Buffer_destroy(tx_buffer);

    return 0;



    And this one shows how all memory allocations can be done within the main function:



    #include <stdio.h>
    #include "buffer.h"

    int main(int argc, char *argv[])

    uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
    struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
    Buffer2_create(rx_buffer, ptr_rx_buffer, 8);

    Buffer2_destroy(rx_buffer);

    return 0;



    And here are the contents of the header file buffer.h:



    #ifndef _buffer_h
    #define _buffer_h

    #include <stdint.h>
    #include <stdlib.h>

    struct Buffer
    uint8_t *buffer;
    size_t size;
    ;

    struct Buffer *Buffer_create(size_t size);

    void Buffer_destroy(struct Buffer *who);

    void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);

    void Buffer2_destroy(struct Buffer *who);

    #endif


    And buffer.c:



    #include <stdint.h>
    #include <assert.h>
    #include <stdlib.h>
    #include "buffer.h"

    struct Buffer *Buffer_create(size_t size)

    struct Buffer *who = malloc(sizeof(struct Buffer));
    assert(who != NULL);

    who->buffer = malloc(sizeof(uint8_t)*size);
    who->size = size;

    return who;


    void Buffer_destroy(struct Buffer *who)

    assert(who != NULL);
    free(who->buffer);
    free(who);


    void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)

    assert(who != NULL);

    who->buffer = buffer;
    who->size = size;


    void Buffer2_destroy(struct Buffer *who)

    assert(who != NULL);
    free(who->buffer);
    free(who);



    The Result



    Both approaches work and the executable files for both end up being the same size.



    My Question



    Will either of these approaches result in memory leaks or poor performance?










    share|improve this question









    New contributor




    David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      1












      1








      1





      $begingroup$


      When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned:



      #include <stdio.h>
      #include "buffer.h"

      int main(int argc, char *argv[])

      struct Buffer *tx_buffer = Buffer_create(8);

      Buffer_destroy(tx_buffer);

      return 0;



      And this one shows how all memory allocations can be done within the main function:



      #include <stdio.h>
      #include "buffer.h"

      int main(int argc, char *argv[])

      uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
      struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
      Buffer2_create(rx_buffer, ptr_rx_buffer, 8);

      Buffer2_destroy(rx_buffer);

      return 0;



      And here are the contents of the header file buffer.h:



      #ifndef _buffer_h
      #define _buffer_h

      #include <stdint.h>
      #include <stdlib.h>

      struct Buffer
      uint8_t *buffer;
      size_t size;
      ;

      struct Buffer *Buffer_create(size_t size);

      void Buffer_destroy(struct Buffer *who);

      void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);

      void Buffer2_destroy(struct Buffer *who);

      #endif


      And buffer.c:



      #include <stdint.h>
      #include <assert.h>
      #include <stdlib.h>
      #include "buffer.h"

      struct Buffer *Buffer_create(size_t size)

      struct Buffer *who = malloc(sizeof(struct Buffer));
      assert(who != NULL);

      who->buffer = malloc(sizeof(uint8_t)*size);
      who->size = size;

      return who;


      void Buffer_destroy(struct Buffer *who)

      assert(who != NULL);
      free(who->buffer);
      free(who);


      void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)

      assert(who != NULL);

      who->buffer = buffer;
      who->size = size;


      void Buffer2_destroy(struct Buffer *who)

      assert(who != NULL);
      free(who->buffer);
      free(who);



      The Result



      Both approaches work and the executable files for both end up being the same size.



      My Question



      Will either of these approaches result in memory leaks or poor performance?










      share|improve this question









      New contributor




      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned:



      #include <stdio.h>
      #include "buffer.h"

      int main(int argc, char *argv[])

      struct Buffer *tx_buffer = Buffer_create(8);

      Buffer_destroy(tx_buffer);

      return 0;



      And this one shows how all memory allocations can be done within the main function:



      #include <stdio.h>
      #include "buffer.h"

      int main(int argc, char *argv[])

      uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8);
      struct Buffer *rx_buffer = malloc(sizeof(struct Buffer));
      Buffer2_create(rx_buffer, ptr_rx_buffer, 8);

      Buffer2_destroy(rx_buffer);

      return 0;



      And here are the contents of the header file buffer.h:



      #ifndef _buffer_h
      #define _buffer_h

      #include <stdint.h>
      #include <stdlib.h>

      struct Buffer
      uint8_t *buffer;
      size_t size;
      ;

      struct Buffer *Buffer_create(size_t size);

      void Buffer_destroy(struct Buffer *who);

      void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size);

      void Buffer2_destroy(struct Buffer *who);

      #endif


      And buffer.c:



      #include <stdint.h>
      #include <assert.h>
      #include <stdlib.h>
      #include "buffer.h"

      struct Buffer *Buffer_create(size_t size)

      struct Buffer *who = malloc(sizeof(struct Buffer));
      assert(who != NULL);

      who->buffer = malloc(sizeof(uint8_t)*size);
      who->size = size;

      return who;


      void Buffer_destroy(struct Buffer *who)

      assert(who != NULL);
      free(who->buffer);
      free(who);


      void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size)

      assert(who != NULL);

      who->buffer = buffer;
      who->size = size;


      void Buffer2_destroy(struct Buffer *who)

      assert(who != NULL);
      free(who->buffer);
      free(who);



      The Result



      Both approaches work and the executable files for both end up being the same size.



      My Question



      Will either of these approaches result in memory leaks or poor performance?







      performance c comparative-review memory-management pointers






      share|improve this question









      New contributor




      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 41 mins ago









      1201ProgramAlarm

      3,7632925




      3,7632925






      New contributor




      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 3 hours ago









      DavidDavid

      1093




      1093




      New contributor




      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          2 Answers
          2






          active

          oldest

          votes


















          3












          $begingroup$

          Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.



          Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.






          share|improve this answer









          $endgroup$




















            0












            $begingroup$

            In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to Buffer must be kept around somehow, even if we would really just want to store the Buffer by value and avoid some unnecessary double-indirection).



            In the second case, the caller does have control, but Buffer2_destroy makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling Buffer2_destroy enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline "allocate and free memory in the same module, at the same level of abstraction", and doesn't get much in return.



            Practically what a user of some buffer may want to do is for example:



            • Having the Buffer as a local variable but its data malloc-ed.

            • Having the Buffer as a local variable and making its data refer to a local array.

            • Save the Buffer into some other struct or array (by value, not a pointer to a Buffer which then points to the data).

            • Using (part of) a static array as the data.

            • Various other such combinations..

            • Allocate both the buffer data and the instance of Buffer in the same allocation.

            Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where "secret malloc" is not appreciated, and custom allocators are commonly used.






            share|improve this answer









            $endgroup$













              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "196"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );






              David is a new contributor. Be nice, and check out our Code of Conduct.









              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217807%2fmalloc-in-main-or-malloc-in-another-function-allocating-memory-for-a-struct-a%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3












              $begingroup$

              Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.



              Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.






              share|improve this answer









              $endgroup$

















                3












                $begingroup$

                Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.



                Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.






                share|improve this answer









                $endgroup$















                  3












                  3








                  3





                  $begingroup$

                  Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.



                  Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.






                  share|improve this answer









                  $endgroup$



                  Looking at the performance, the two versions should perform just about identically. The second version has one less call/return, which can save a couple of CPU cycles, but if you have it multiple places in your code the additional code bytes and cache misses can overshadow that. Either way you probably won't notice a difference.



                  Looking at readability and maintainability, the first version is much better. You know at a glance what it is doing (rather than looking at several lines to figure it all out), you won't forget any important steps, and error checking is much easier since most of it can be handled in one place (excepting the last check for successful creation of the buffer). Debugging can also be easier, since you can set a breakpoint on the creation or destruction functions if necessary.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 33 mins ago









                  1201ProgramAlarm1201ProgramAlarm

                  3,7632925




                  3,7632925























                      0












                      $begingroup$

                      In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to Buffer must be kept around somehow, even if we would really just want to store the Buffer by value and avoid some unnecessary double-indirection).



                      In the second case, the caller does have control, but Buffer2_destroy makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling Buffer2_destroy enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline "allocate and free memory in the same module, at the same level of abstraction", and doesn't get much in return.



                      Practically what a user of some buffer may want to do is for example:



                      • Having the Buffer as a local variable but its data malloc-ed.

                      • Having the Buffer as a local variable and making its data refer to a local array.

                      • Save the Buffer into some other struct or array (by value, not a pointer to a Buffer which then points to the data).

                      • Using (part of) a static array as the data.

                      • Various other such combinations..

                      • Allocate both the buffer data and the instance of Buffer in the same allocation.

                      Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where "secret malloc" is not appreciated, and custom allocators are commonly used.






                      share|improve this answer









                      $endgroup$

















                        0












                        $begingroup$

                        In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to Buffer must be kept around somehow, even if we would really just want to store the Buffer by value and avoid some unnecessary double-indirection).



                        In the second case, the caller does have control, but Buffer2_destroy makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling Buffer2_destroy enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline "allocate and free memory in the same module, at the same level of abstraction", and doesn't get much in return.



                        Practically what a user of some buffer may want to do is for example:



                        • Having the Buffer as a local variable but its data malloc-ed.

                        • Having the Buffer as a local variable and making its data refer to a local array.

                        • Save the Buffer into some other struct or array (by value, not a pointer to a Buffer which then points to the data).

                        • Using (part of) a static array as the data.

                        • Various other such combinations..

                        • Allocate both the buffer data and the instance of Buffer in the same allocation.

                        Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where "secret malloc" is not appreciated, and custom allocators are commonly used.






                        share|improve this answer









                        $endgroup$















                          0












                          0








                          0





                          $begingroup$

                          In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to Buffer must be kept around somehow, even if we would really just want to store the Buffer by value and avoid some unnecessary double-indirection).



                          In the second case, the caller does have control, but Buffer2_destroy makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling Buffer2_destroy enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline "allocate and free memory in the same module, at the same level of abstraction", and doesn't get much in return.



                          Practically what a user of some buffer may want to do is for example:



                          • Having the Buffer as a local variable but its data malloc-ed.

                          • Having the Buffer as a local variable and making its data refer to a local array.

                          • Save the Buffer into some other struct or array (by value, not a pointer to a Buffer which then points to the data).

                          • Using (part of) a static array as the data.

                          • Various other such combinations..

                          • Allocate both the buffer data and the instance of Buffer in the same allocation.

                          Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where "secret malloc" is not appreciated, and custom allocators are commonly used.






                          share|improve this answer









                          $endgroup$



                          In the first case, the caller is not given any control over allocation. This limits freedom and (therefore) performance: there is no control over the number of dynamic allocations or over which memory is used for what purpose, and there are limits on how the handle to the buffer can be stored (the returned pointer to Buffer must be kept around somehow, even if we would really just want to store the Buffer by value and avoid some unnecessary double-indirection).



                          In the second case, the caller does have control, but Buffer2_destroy makes a very limiting assumption about how the memory was allocated so in the end the caller still has no choice. Of course by looking into the implementation details, one could see that simply not calling Buffer2_destroy enables some freedom again, but this would probably be considered a hack. All in all this approach violates the guideline "allocate and free memory in the same module, at the same level of abstraction", and doesn't get much in return.



                          Practically what a user of some buffer may want to do is for example:



                          • Having the Buffer as a local variable but its data malloc-ed.

                          • Having the Buffer as a local variable and making its data refer to a local array.

                          • Save the Buffer into some other struct or array (by value, not a pointer to a Buffer which then points to the data).

                          • Using (part of) a static array as the data.

                          • Various other such combinations..

                          • Allocate both the buffer data and the instance of Buffer in the same allocation.

                          Which is why a common advice is, where possible, do not allocate or deallocate memory, use memory supplied by the caller. This applies especially to performance-sensitive settings, where "secret malloc" is not appreciated, and custom allocators are commonly used.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 23 mins ago









                          haroldharold

                          1,47368




                          1,47368




















                              David is a new contributor. Be nice, and check out our Code of Conduct.









                              draft saved

                              draft discarded


















                              David is a new contributor. Be nice, and check out our Code of Conduct.












                              David is a new contributor. Be nice, and check out our Code of Conduct.











                              David is a new contributor. Be nice, and check out our Code of Conduct.














                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217807%2fmalloc-in-main-or-malloc-in-another-function-allocating-memory-for-a-struct-a%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                              Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                              Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр