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;
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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
variable is made. - Program 2 calls
B()
, which creates a locally stored copy of the valuenetWorth
on its stack memory, increments this local copy, then returns it back toA()
asresult
. This is an example of pass by value.- Does the local copy of
worthRef
get destroyed when it's returned?
- Does the local copy of
- 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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
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
add a comment |
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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
variable is made. - Program 2 calls
B()
, which creates a locally stored copy of the valuenetWorth
on its stack memory, increments this local copy, then returns it back toA()
asresult
. This is an example of pass by value.- Does the local copy of
worthRef
get destroyed when it's returned?
- Does the local copy of
- 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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
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
1
pass by reference does not exist in C. Also, replaceint *netWorth = (int *) malloc(sizeof(int));
withint *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 yourmalloc
ated 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
add a comment |
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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
variable is made. - Program 2 calls
B()
, which creates a locally stored copy of the valuenetWorth
on its stack memory, increments this local copy, then returns it back toA()
asresult
. This is an example of pass by value.- Does the local copy of
worthRef
get destroyed when it's returned?
- Does the local copy of
- 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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
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
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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
variable is made. - Program 2 calls
B()
, which creates a locally stored copy of the valuenetWorth
on its stack memory, increments this local copy, then returns it back toA()
asresult
. This is an example of pass by value.- Does the local copy of
worthRef
get destroyed when it's returned?
- Does the local copy of
- 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 variablenetWorth
. This is an example of pass by reference. No copy of thenetWorth
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
c malloc
asked Mar 24 at 19:59
WaterGuyWaterGuy
597
597
1
pass by reference does not exist in C. Also, replaceint *netWorth = (int *) malloc(sizeof(int));
withint *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 yourmalloc
ated 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
add a comment |
1
pass by reference does not exist in C. Also, replaceint *netWorth = (int *) malloc(sizeof(int));
withint *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 yourmalloc
ated 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
malloc
ated 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
malloc
ated 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
add a comment |
2 Answers
2
active
oldest
votes
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,
If you can declare a local variable instead of allocating heap, you generally should.
If you can avoid declaring a global variable, you generally should.
add a comment |
Checking your understanding:
- Program 1 allocates memory
onwithin the function stack frame ofA()
for the variable netWorth, and passes the address ofnetWorth
as a pointer to thisstackmemory address to functionB()
allowingB()
to directly modify the value for the variable netWorth stored at that memory address. This is an example ofpass by referencepassing 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 toA()
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 thisheapmemory 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 withmalloc/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 alsostatic
andthread local
storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objectsThis 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 bymalloc
is used throughout to reference this memory location.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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,
If you can declare a local variable instead of allocating heap, you generally should.
If you can avoid declaring a global variable, you generally should.
add a comment |
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,
If you can declare a local variable instead of allocating heap, you generally should.
If you can avoid declaring a global variable, you generally should.
add a comment |
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,
If you can declare a local variable instead of allocating heap, you generally should.
If you can avoid declaring a global variable, you generally should.
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,
If you can declare a local variable instead of allocating heap, you generally should.
If you can avoid declaring a global variable, you generally should.
edited Mar 24 at 20:15
answered Mar 24 at 20:08
paulsm4paulsm4
81.7k9105134
81.7k9105134
add a comment |
add a comment |
Checking your understanding:
- Program 1 allocates memory
onwithin the function stack frame ofA()
for the variable netWorth, and passes the address ofnetWorth
as a pointer to thisstackmemory address to functionB()
allowingB()
to directly modify the value for the variable netWorth stored at that memory address. This is an example ofpass by referencepassing 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 toA()
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 thisheapmemory 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 withmalloc/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 alsostatic
andthread local
storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objectsThis 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 bymalloc
is used throughout to reference this memory location.
add a comment |
Checking your understanding:
- Program 1 allocates memory
onwithin the function stack frame ofA()
for the variable netWorth, and passes the address ofnetWorth
as a pointer to thisstackmemory address to functionB()
allowingB()
to directly modify the value for the variable netWorth stored at that memory address. This is an example ofpass by referencepassing 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 toA()
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 thisheapmemory 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 withmalloc/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 alsostatic
andthread local
storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objectsThis 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 bymalloc
is used throughout to reference this memory location.
add a comment |
Checking your understanding:
- Program 1 allocates memory
onwithin the function stack frame ofA()
for the variable netWorth, and passes the address ofnetWorth
as a pointer to thisstackmemory address to functionB()
allowingB()
to directly modify the value for the variable netWorth stored at that memory address. This is an example ofpass by referencepassing 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 toA()
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 thisheapmemory 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 withmalloc/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 alsostatic
andthread local
storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objectsThis 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 bymalloc
is used throughout to reference this memory location.
Checking your understanding:
- Program 1 allocates memory
onwithin the function stack frame ofA()
for the variable netWorth, and passes the address ofnetWorth
as a pointer to thisstackmemory address to functionB()
allowingB()
to directly modify the value for the variable netWorth stored at that memory address. This is an example ofpass by referencepassing 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 toA()
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 thisheapmemory 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 withmalloc/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 alsostatic
andthread local
storage durations not relevant here) See: C11 Standard - 6.2.4 Storage durations of objectsThis 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 bymalloc
is used throughout to reference this memory location.
edited Mar 24 at 20:43
answered Mar 24 at 20:37
David C. RankinDavid C. Rankin
45.5k33253
45.5k33253
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
pass by reference does not exist in C. Also, replace
int *netWorth = (int *) malloc(sizeof(int));
withint *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
malloc
ated 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