Pass by reference and use of mallocScope vs life of variable in CDo I cast the result of malloc?Difference between malloc and calloc?Improve INSERT-per-second performance of SQLite?malloc() vs. HeapAlloc()realloc and malloc functionsWhere in memory are my variables stored in C?local variable memory and malloced memory locationsbrk and malloc in cUnderstanding pointers & mallocusing malloc to allocate pointers

Electricity free spaceship

Why can I traceroute to this IP address, but not ping?

Reactive Programming

How to hide rifle during medieval town entrance inspection?

Can all groups be thought of as the symmetries of a geometrical object?

Can the removal of a duty-free sales trolley result in a measurable reduction in emissions?

Are polynomials with the same roots identical?

If there's something that implicates the president why is there then a national security issue? (John Dowd)

Ability To Change Root User Password (Vulnerability?)

What would be the way to say "just saying" in German? (Not the literal translation)

What is the color of artificial intelligence?

What aircraft was used as Air Force One for the flight between Southampton and Shannon?

How to publish items after pipeline is finished?

Can a human be transformed into a Mind Flayer?

Is using 'echo' to display attacker-controlled data on the terminal dangerous?

Non-aqueous eyes?

How do free-speech protections in the United States apply in public to corporate misrepresentations?

Is it possible to fly backward if you have really strong headwind?

The Frozen Wastes

What does 思ってやっている mean?

Can I utilise a baking stone to make crepes?

60s or 70s novel about Empire of Man making 1st contact with 1st discovered alien race

UTC timestamp format for launch vehicles

How creative should the DM let an artificer be in terms of what they can build?



Pass by reference and use of malloc


Scope vs life of variable in CDo I cast the result of malloc?Difference between malloc and calloc?Improve INSERT-per-second performance of SQLite?malloc() vs. HeapAlloc()realloc and malloc functionsWhere in memory are my variables stored in C?local variable memory and malloced memory locationsbrk and malloc in cUnderstanding pointers & mallocusing malloc to allocate pointers






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm a beginner to the C programming language. I sort of understand the general definition of stack memory, heap memory, malloc, pointers, and memory addresses. But I'm a little overwhelmed on understanding when to use each technique in practice and the difference between them.



I've written three small programs to serve as examples. They all do the same thing, and I'd like a little commentary and explanation about what the difference between them is. I do realize that's a naive programming question, but I'm hoping to connect some basic dots here.



Program 1:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated
on the stack in A.
*/
*worthRef = *worthRef + 1;


void A()
int netWorth = 20;
B(&netWorth);

printf("%d", netWorth); // Prints 21


int main()
A();



Program 2:



int B (int worthRef) 
/* worthRef is now a local variable. If
I return it, will it get destroyed
once B finishes execution?
*/
worthRef = worthRef + 1;
return (worthRef);


void A()
int netWorth = 20;
int result = B(netWorth);

printf("%d", result); // Also prints 21


int main()
A();



Program 3:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated on
the heap.
*/
*worthRef = *worthRef + 1;


void A()
int *netWorth = (int *) malloc(sizeof(int));
*netWorth = 20;

B(netWorth);

printf("%d", *netWorth); // Also prints 21

free(netWorth);


int main()
A();



Please check my understanding:



  • Program 1 allocates memory on the stack for the variable netWorth, and uses a pointer to this stack memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns it back to A() as result. This is an example of pass by value.

    • Does the local copy of worthRef get destroyed when it's returned?


  • Program 3 allocates memory on the heap for the variable netWorth, variable, and uses a pointer to this heap memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

My main point of confusion is between Program 1 and Program 3. Both are passing pointers around; it's just that one is passing a pointer to a stack variable versus one passing a pointer to a heap variable, right? But in this situation, why do I even need the heap? I just want to have a single function to change a single value, directly, which I can do just fine without malloc.



The heap allows the programmer to choose the lifetime of the variable, right? In what circumstances would the programmer want to just keep a variable around (e.g. netWorth in this case)? Why not just make it a global variable in that case?










share|improve this question

















  • 1





    pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

    – tilz0R
    Mar 24 at 20:03












  • There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

    – Antti Haapala
    Mar 24 at 20:06












  • @tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

    – Chris Dodd
    Mar 24 at 20:12











  • You might be interested in the difference between scope and lifetime

    – Chris Dodd
    Mar 24 at 20:20

















1















I'm a beginner to the C programming language. I sort of understand the general definition of stack memory, heap memory, malloc, pointers, and memory addresses. But I'm a little overwhelmed on understanding when to use each technique in practice and the difference between them.



I've written three small programs to serve as examples. They all do the same thing, and I'd like a little commentary and explanation about what the difference between them is. I do realize that's a naive programming question, but I'm hoping to connect some basic dots here.



Program 1:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated
on the stack in A.
*/
*worthRef = *worthRef + 1;


void A()
int netWorth = 20;
B(&netWorth);

printf("%d", netWorth); // Prints 21


int main()
A();



Program 2:



int B (int worthRef) 
/* worthRef is now a local variable. If
I return it, will it get destroyed
once B finishes execution?
*/
worthRef = worthRef + 1;
return (worthRef);


void A()
int netWorth = 20;
int result = B(netWorth);

printf("%d", result); // Also prints 21


int main()
A();



Program 3:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated on
the heap.
*/
*worthRef = *worthRef + 1;


void A()
int *netWorth = (int *) malloc(sizeof(int));
*netWorth = 20;

B(netWorth);

printf("%d", *netWorth); // Also prints 21

free(netWorth);


int main()
A();



Please check my understanding:



  • Program 1 allocates memory on the stack for the variable netWorth, and uses a pointer to this stack memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns it back to A() as result. This is an example of pass by value.

    • Does the local copy of worthRef get destroyed when it's returned?


  • Program 3 allocates memory on the heap for the variable netWorth, variable, and uses a pointer to this heap memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

My main point of confusion is between Program 1 and Program 3. Both are passing pointers around; it's just that one is passing a pointer to a stack variable versus one passing a pointer to a heap variable, right? But in this situation, why do I even need the heap? I just want to have a single function to change a single value, directly, which I can do just fine without malloc.



The heap allows the programmer to choose the lifetime of the variable, right? In what circumstances would the programmer want to just keep a variable around (e.g. netWorth in this case)? Why not just make it a global variable in that case?










share|improve this question

















  • 1





    pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

    – tilz0R
    Mar 24 at 20:03












  • There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

    – Antti Haapala
    Mar 24 at 20:06












  • @tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

    – Chris Dodd
    Mar 24 at 20:12











  • You might be interested in the difference between scope and lifetime

    – Chris Dodd
    Mar 24 at 20:20













1












1








1


1






I'm a beginner to the C programming language. I sort of understand the general definition of stack memory, heap memory, malloc, pointers, and memory addresses. But I'm a little overwhelmed on understanding when to use each technique in practice and the difference between them.



I've written three small programs to serve as examples. They all do the same thing, and I'd like a little commentary and explanation about what the difference between them is. I do realize that's a naive programming question, but I'm hoping to connect some basic dots here.



Program 1:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated
on the stack in A.
*/
*worthRef = *worthRef + 1;


void A()
int netWorth = 20;
B(&netWorth);

printf("%d", netWorth); // Prints 21


int main()
A();



Program 2:



int B (int worthRef) 
/* worthRef is now a local variable. If
I return it, will it get destroyed
once B finishes execution?
*/
worthRef = worthRef + 1;
return (worthRef);


void A()
int netWorth = 20;
int result = B(netWorth);

printf("%d", result); // Also prints 21


int main()
A();



Program 3:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated on
the heap.
*/
*worthRef = *worthRef + 1;


void A()
int *netWorth = (int *) malloc(sizeof(int));
*netWorth = 20;

B(netWorth);

printf("%d", *netWorth); // Also prints 21

free(netWorth);


int main()
A();



Please check my understanding:



  • Program 1 allocates memory on the stack for the variable netWorth, and uses a pointer to this stack memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns it back to A() as result. This is an example of pass by value.

    • Does the local copy of worthRef get destroyed when it's returned?


  • Program 3 allocates memory on the heap for the variable netWorth, variable, and uses a pointer to this heap memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

My main point of confusion is between Program 1 and Program 3. Both are passing pointers around; it's just that one is passing a pointer to a stack variable versus one passing a pointer to a heap variable, right? But in this situation, why do I even need the heap? I just want to have a single function to change a single value, directly, which I can do just fine without malloc.



The heap allows the programmer to choose the lifetime of the variable, right? In what circumstances would the programmer want to just keep a variable around (e.g. netWorth in this case)? Why not just make it a global variable in that case?










share|improve this question














I'm a beginner to the C programming language. I sort of understand the general definition of stack memory, heap memory, malloc, pointers, and memory addresses. But I'm a little overwhelmed on understanding when to use each technique in practice and the difference between them.



I've written three small programs to serve as examples. They all do the same thing, and I'd like a little commentary and explanation about what the difference between them is. I do realize that's a naive programming question, but I'm hoping to connect some basic dots here.



Program 1:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated
on the stack in A.
*/
*worthRef = *worthRef + 1;


void A()
int netWorth = 20;
B(&netWorth);

printf("%d", netWorth); // Prints 21


int main()
A();



Program 2:



int B (int worthRef) 
/* worthRef is now a local variable. If
I return it, will it get destroyed
once B finishes execution?
*/
worthRef = worthRef + 1;
return (worthRef);


void A()
int netWorth = 20;
int result = B(netWorth);

printf("%d", result); // Also prints 21


int main()
A();



Program 3:



void B (int* worthRef) 
/* worthRef is a pointer to the
netWorth variable allocated on
the heap.
*/
*worthRef = *worthRef + 1;


void A()
int *netWorth = (int *) malloc(sizeof(int));
*netWorth = 20;

B(netWorth);

printf("%d", *netWorth); // Also prints 21

free(netWorth);


int main()
A();



Please check my understanding:



  • Program 1 allocates memory on the stack for the variable netWorth, and uses a pointer to this stack memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns it back to A() as result. This is an example of pass by value.

    • Does the local copy of worthRef get destroyed when it's returned?


  • Program 3 allocates memory on the heap for the variable netWorth, variable, and uses a pointer to this heap memory address to directly modify the variable netWorth. This is an example of pass by reference. No copy of the netWorth variable is made.

My main point of confusion is between Program 1 and Program 3. Both are passing pointers around; it's just that one is passing a pointer to a stack variable versus one passing a pointer to a heap variable, right? But in this situation, why do I even need the heap? I just want to have a single function to change a single value, directly, which I can do just fine without malloc.



The heap allows the programmer to choose the lifetime of the variable, right? In what circumstances would the programmer want to just keep a variable around (e.g. netWorth in this case)? Why not just make it a global variable in that case?







c malloc






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 19:59









WaterGuyWaterGuy

597




597







  • 1





    pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

    – tilz0R
    Mar 24 at 20:03












  • There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

    – Antti Haapala
    Mar 24 at 20:06












  • @tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

    – Chris Dodd
    Mar 24 at 20:12











  • You might be interested in the difference between scope and lifetime

    – Chris Dodd
    Mar 24 at 20:20












  • 1





    pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

    – tilz0R
    Mar 24 at 20:03












  • There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

    – Antti Haapala
    Mar 24 at 20:06












  • @tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

    – Chris Dodd
    Mar 24 at 20:12











  • You might be interested in the difference between scope and lifetime

    – Chris Dodd
    Mar 24 at 20:20







1




1





pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

– tilz0R
Mar 24 at 20:03






pass by reference does not exist in C. Also, replace int *netWorth = (int *) malloc(sizeof(int)); with int *netWorth = malloc(sizeof(*netWorth));

– tilz0R
Mar 24 at 20:03














There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

– Antti Haapala
Mar 24 at 20:06






There are no "allocates memory on stack or heap". There are only storage durations: static, allocated, thread-local and global. The compiler is free to do as it pleases - most importantly your mallocated object might not be ever allocated on heap.

– Antti Haapala
Mar 24 at 20:06














@tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

– Chris Dodd
Mar 24 at 20:12





@tilz0R: The term 'pass by reference' is commonly used in C for this kind of thing where a pointer is passed to a function. Its totally different from 'pass by reference' in C++, but C (and the term) existed long before C++ did.

– Chris Dodd
Mar 24 at 20:12













You might be interested in the difference between scope and lifetime

– Chris Dodd
Mar 24 at 20:20





You might be interested in the difference between scope and lifetime

– Chris Dodd
Mar 24 at 20:20












2 Answers
2






active

oldest

votes


















1















I sort of understand the general definition of stack memory, heap
memory, malloc, pointers, and memory addresses... I'd like a little
commentary and explanation about what the difference between them
is...




<= OK...




Program 1 allocates memory on the stack for the variable netWorth, and
uses a pointer to this stack memory address to directly modify the
variable netWorth. This is an example of pass by reference.




<= Absolutely correct!




Q: Program 2 ... Does the local copy of worthRef get destroyed when it's returned?




A: int netWorth exists only within the scope of A(), whicn included the invocation of B().




Program 1 and Program 3 ... one is passing a pointer to a stack variable versus one passing a pointer to a heap variable.
Q: But in this situation, why do I even need the heap?




A: You don't. It's perfectly OK (arguably preferable) to simply take addressof (&) int, as you did in Program 1.




Q: The heap allows the programmer to choose the lifetime of the variable, right?




A: Yes, that's one aspect of allocating memory dynamically. You are correct.




Q: Why not just make it a global variable in that case?




A: Yes, that's another alternative.



The answer to any question "Why choose one design alternative over another?" is usually "It depends".



For example, maybe you can't just declare everything "local variable" because you're environment happens to have a very small, limited stack. It happens :)



In general,



  1. If you can declare a local variable instead of allocating heap, you generally should.


  2. If you can avoid declaring a global variable, you generally should.






share|improve this answer
































    1














    Checking your understanding:



    • Program 1 allocates memory on within the function stack frame of A() for the variable netWorth, and passes the address of netWorth as a pointer to this stack memory address to function B() allowing B() to directly modify the value for the variable netWorth stored at that memory address. This is an example of pass by reference passing the 'address of' a variable by value. (there is no pass by reference in C -- it's all pass by value) No copy of the netWorth variable is made.

    • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns the integer back to A() as result. (a function can always return its own type) This is an example of pass by value (because there is only pass by value in C).

    (Does the local copy of worthRef get destroyed when it's returned? - answer yes, but since a function can always return its own type, it can return the int value to A() [which is handled by the calling convention for the platform])



    • Program 3 allocates memory on the heap for the variable netWorth, and uses a pointer to this heap memory address to directly modify the variable netWorth. While "stack/heap" are commonly used terms, C has no concept of stack or heap, the distiction is that variables are either declared with Automatic Storage Duration which is limited to the scope within which they are declared --or-- when you allocate with malloc/calloc/realloc, the block of memory has Allocated Storage Duration which is good for the life of the program or until the block of memory is freed. (there are also static and thread local storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objects This is an example of pass by reference. (It's all pass by Value!) No copy of the netWorth variable is made. A pointer to the address originally returned by malloc is used throughout to reference this memory location.





    share|improve this answer

























      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: "1"
      ;
      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: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328006%2fpass-by-reference-and-use-of-malloc%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









      1















      I sort of understand the general definition of stack memory, heap
      memory, malloc, pointers, and memory addresses... I'd like a little
      commentary and explanation about what the difference between them
      is...




      <= OK...




      Program 1 allocates memory on the stack for the variable netWorth, and
      uses a pointer to this stack memory address to directly modify the
      variable netWorth. This is an example of pass by reference.




      <= Absolutely correct!




      Q: Program 2 ... Does the local copy of worthRef get destroyed when it's returned?




      A: int netWorth exists only within the scope of A(), whicn included the invocation of B().




      Program 1 and Program 3 ... one is passing a pointer to a stack variable versus one passing a pointer to a heap variable.
      Q: But in this situation, why do I even need the heap?




      A: You don't. It's perfectly OK (arguably preferable) to simply take addressof (&) int, as you did in Program 1.




      Q: The heap allows the programmer to choose the lifetime of the variable, right?




      A: Yes, that's one aspect of allocating memory dynamically. You are correct.




      Q: Why not just make it a global variable in that case?




      A: Yes, that's another alternative.



      The answer to any question "Why choose one design alternative over another?" is usually "It depends".



      For example, maybe you can't just declare everything "local variable" because you're environment happens to have a very small, limited stack. It happens :)



      In general,



      1. If you can declare a local variable instead of allocating heap, you generally should.


      2. If you can avoid declaring a global variable, you generally should.






      share|improve this answer





























        1















        I sort of understand the general definition of stack memory, heap
        memory, malloc, pointers, and memory addresses... I'd like a little
        commentary and explanation about what the difference between them
        is...




        <= OK...




        Program 1 allocates memory on the stack for the variable netWorth, and
        uses a pointer to this stack memory address to directly modify the
        variable netWorth. This is an example of pass by reference.




        <= Absolutely correct!




        Q: Program 2 ... Does the local copy of worthRef get destroyed when it's returned?




        A: int netWorth exists only within the scope of A(), whicn included the invocation of B().




        Program 1 and Program 3 ... one is passing a pointer to a stack variable versus one passing a pointer to a heap variable.
        Q: But in this situation, why do I even need the heap?




        A: You don't. It's perfectly OK (arguably preferable) to simply take addressof (&) int, as you did in Program 1.




        Q: The heap allows the programmer to choose the lifetime of the variable, right?




        A: Yes, that's one aspect of allocating memory dynamically. You are correct.




        Q: Why not just make it a global variable in that case?




        A: Yes, that's another alternative.



        The answer to any question "Why choose one design alternative over another?" is usually "It depends".



        For example, maybe you can't just declare everything "local variable" because you're environment happens to have a very small, limited stack. It happens :)



        In general,



        1. If you can declare a local variable instead of allocating heap, you generally should.


        2. If you can avoid declaring a global variable, you generally should.






        share|improve this answer



























          1












          1








          1








          I sort of understand the general definition of stack memory, heap
          memory, malloc, pointers, and memory addresses... I'd like a little
          commentary and explanation about what the difference between them
          is...




          <= OK...




          Program 1 allocates memory on the stack for the variable netWorth, and
          uses a pointer to this stack memory address to directly modify the
          variable netWorth. This is an example of pass by reference.




          <= Absolutely correct!




          Q: Program 2 ... Does the local copy of worthRef get destroyed when it's returned?




          A: int netWorth exists only within the scope of A(), whicn included the invocation of B().




          Program 1 and Program 3 ... one is passing a pointer to a stack variable versus one passing a pointer to a heap variable.
          Q: But in this situation, why do I even need the heap?




          A: You don't. It's perfectly OK (arguably preferable) to simply take addressof (&) int, as you did in Program 1.




          Q: The heap allows the programmer to choose the lifetime of the variable, right?




          A: Yes, that's one aspect of allocating memory dynamically. You are correct.




          Q: Why not just make it a global variable in that case?




          A: Yes, that's another alternative.



          The answer to any question "Why choose one design alternative over another?" is usually "It depends".



          For example, maybe you can't just declare everything "local variable" because you're environment happens to have a very small, limited stack. It happens :)



          In general,



          1. If you can declare a local variable instead of allocating heap, you generally should.


          2. If you can avoid declaring a global variable, you generally should.






          share|improve this answer
















          I sort of understand the general definition of stack memory, heap
          memory, malloc, pointers, and memory addresses... I'd like a little
          commentary and explanation about what the difference between them
          is...




          <= OK...




          Program 1 allocates memory on the stack for the variable netWorth, and
          uses a pointer to this stack memory address to directly modify the
          variable netWorth. This is an example of pass by reference.




          <= Absolutely correct!




          Q: Program 2 ... Does the local copy of worthRef get destroyed when it's returned?




          A: int netWorth exists only within the scope of A(), whicn included the invocation of B().




          Program 1 and Program 3 ... one is passing a pointer to a stack variable versus one passing a pointer to a heap variable.
          Q: But in this situation, why do I even need the heap?




          A: You don't. It's perfectly OK (arguably preferable) to simply take addressof (&) int, as you did in Program 1.




          Q: The heap allows the programmer to choose the lifetime of the variable, right?




          A: Yes, that's one aspect of allocating memory dynamically. You are correct.




          Q: Why not just make it a global variable in that case?




          A: Yes, that's another alternative.



          The answer to any question "Why choose one design alternative over another?" is usually "It depends".



          For example, maybe you can't just declare everything "local variable" because you're environment happens to have a very small, limited stack. It happens :)



          In general,



          1. If you can declare a local variable instead of allocating heap, you generally should.


          2. If you can avoid declaring a global variable, you generally should.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 20:15

























          answered Mar 24 at 20:08









          paulsm4paulsm4

          81.7k9105134




          81.7k9105134























              1














              Checking your understanding:



              • Program 1 allocates memory on within the function stack frame of A() for the variable netWorth, and passes the address of netWorth as a pointer to this stack memory address to function B() allowing B() to directly modify the value for the variable netWorth stored at that memory address. This is an example of pass by reference passing the 'address of' a variable by value. (there is no pass by reference in C -- it's all pass by value) No copy of the netWorth variable is made.

              • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns the integer back to A() as result. (a function can always return its own type) This is an example of pass by value (because there is only pass by value in C).

              (Does the local copy of worthRef get destroyed when it's returned? - answer yes, but since a function can always return its own type, it can return the int value to A() [which is handled by the calling convention for the platform])



              • Program 3 allocates memory on the heap for the variable netWorth, and uses a pointer to this heap memory address to directly modify the variable netWorth. While "stack/heap" are commonly used terms, C has no concept of stack or heap, the distiction is that variables are either declared with Automatic Storage Duration which is limited to the scope within which they are declared --or-- when you allocate with malloc/calloc/realloc, the block of memory has Allocated Storage Duration which is good for the life of the program or until the block of memory is freed. (there are also static and thread local storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objects This is an example of pass by reference. (It's all pass by Value!) No copy of the netWorth variable is made. A pointer to the address originally returned by malloc is used throughout to reference this memory location.





              share|improve this answer





























                1














                Checking your understanding:



                • Program 1 allocates memory on within the function stack frame of A() for the variable netWorth, and passes the address of netWorth as a pointer to this stack memory address to function B() allowing B() to directly modify the value for the variable netWorth stored at that memory address. This is an example of pass by reference passing the 'address of' a variable by value. (there is no pass by reference in C -- it's all pass by value) No copy of the netWorth variable is made.

                • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns the integer back to A() as result. (a function can always return its own type) This is an example of pass by value (because there is only pass by value in C).

                (Does the local copy of worthRef get destroyed when it's returned? - answer yes, but since a function can always return its own type, it can return the int value to A() [which is handled by the calling convention for the platform])



                • Program 3 allocates memory on the heap for the variable netWorth, and uses a pointer to this heap memory address to directly modify the variable netWorth. While "stack/heap" are commonly used terms, C has no concept of stack or heap, the distiction is that variables are either declared with Automatic Storage Duration which is limited to the scope within which they are declared --or-- when you allocate with malloc/calloc/realloc, the block of memory has Allocated Storage Duration which is good for the life of the program or until the block of memory is freed. (there are also static and thread local storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objects This is an example of pass by reference. (It's all pass by Value!) No copy of the netWorth variable is made. A pointer to the address originally returned by malloc is used throughout to reference this memory location.





                share|improve this answer



























                  1












                  1








                  1







                  Checking your understanding:



                  • Program 1 allocates memory on within the function stack frame of A() for the variable netWorth, and passes the address of netWorth as a pointer to this stack memory address to function B() allowing B() to directly modify the value for the variable netWorth stored at that memory address. This is an example of pass by reference passing the 'address of' a variable by value. (there is no pass by reference in C -- it's all pass by value) No copy of the netWorth variable is made.

                  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns the integer back to A() as result. (a function can always return its own type) This is an example of pass by value (because there is only pass by value in C).

                  (Does the local copy of worthRef get destroyed when it's returned? - answer yes, but since a function can always return its own type, it can return the int value to A() [which is handled by the calling convention for the platform])



                  • Program 3 allocates memory on the heap for the variable netWorth, and uses a pointer to this heap memory address to directly modify the variable netWorth. While "stack/heap" are commonly used terms, C has no concept of stack or heap, the distiction is that variables are either declared with Automatic Storage Duration which is limited to the scope within which they are declared --or-- when you allocate with malloc/calloc/realloc, the block of memory has Allocated Storage Duration which is good for the life of the program or until the block of memory is freed. (there are also static and thread local storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objects This is an example of pass by reference. (It's all pass by Value!) No copy of the netWorth variable is made. A pointer to the address originally returned by malloc is used throughout to reference this memory location.





                  share|improve this answer















                  Checking your understanding:



                  • Program 1 allocates memory on within the function stack frame of A() for the variable netWorth, and passes the address of netWorth as a pointer to this stack memory address to function B() allowing B() to directly modify the value for the variable netWorth stored at that memory address. This is an example of pass by reference passing the 'address of' a variable by value. (there is no pass by reference in C -- it's all pass by value) No copy of the netWorth variable is made.

                  • Program 2 calls B(), which creates a locally stored copy of the value netWorth on its stack memory, increments this local copy, then returns the integer back to A() as result. (a function can always return its own type) This is an example of pass by value (because there is only pass by value in C).

                  (Does the local copy of worthRef get destroyed when it's returned? - answer yes, but since a function can always return its own type, it can return the int value to A() [which is handled by the calling convention for the platform])



                  • Program 3 allocates memory on the heap for the variable netWorth, and uses a pointer to this heap memory address to directly modify the variable netWorth. While "stack/heap" are commonly used terms, C has no concept of stack or heap, the distiction is that variables are either declared with Automatic Storage Duration which is limited to the scope within which they are declared --or-- when you allocate with malloc/calloc/realloc, the block of memory has Allocated Storage Duration which is good for the life of the program or until the block of memory is freed. (there are also static and thread local storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objects This is an example of pass by reference. (It's all pass by Value!) No copy of the netWorth variable is made. A pointer to the address originally returned by malloc is used throughout to reference this memory location.






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 24 at 20:43

























                  answered Mar 24 at 20:37









                  David C. RankinDavid C. Rankin

                  45.5k33253




                  45.5k33253



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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.

                      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%2fstackoverflow.com%2fquestions%2f55328006%2fpass-by-reference-and-use-of-malloc%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

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현