Dynamic memory access only works inside function












16















This question is meant to be used as a canonical duplicate for this FAQ:



I am allocating data dynamically inside a function and everything works well, but only inside the function where the allocation takes place. When I attempt to use the same data outside the function, I get crashes or other unexpected program behavior.



Here is a MCVE:



#include <stdlib.h>
#include <stdio.h>

void create_array (int* data, int size)
{
data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);
}

void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("n");
}

int main (void)
{
int* data;
const int size = 5;

create_array(data, size);
print_array(data, size); // crash here

free(data);
}


Whenever print_array is called from inside the create_array function, I get the expected output 0 1 2 3 4, but when I call it from main, I get a program crash.



What is the reason for this?










share|improve this question




















  • 4





    I almost downvoted you for making such a stupid mistake :)

    – Jean-François Fabre
    Sep 14 '16 at 9:25











  • @Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

    – Lundin
    Sep 14 '16 at 9:27






  • 2





    I think can be better hosted on Documentation Beta.

    – LPs
    Sep 14 '16 at 9:27











  • @LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

    – Lundin
    Sep 14 '16 at 9:30













  • You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

    – Nik-Lz
    Mar 17 '17 at 11:53
















16















This question is meant to be used as a canonical duplicate for this FAQ:



I am allocating data dynamically inside a function and everything works well, but only inside the function where the allocation takes place. When I attempt to use the same data outside the function, I get crashes or other unexpected program behavior.



Here is a MCVE:



#include <stdlib.h>
#include <stdio.h>

void create_array (int* data, int size)
{
data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);
}

void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("n");
}

int main (void)
{
int* data;
const int size = 5;

create_array(data, size);
print_array(data, size); // crash here

free(data);
}


Whenever print_array is called from inside the create_array function, I get the expected output 0 1 2 3 4, but when I call it from main, I get a program crash.



What is the reason for this?










share|improve this question




















  • 4





    I almost downvoted you for making such a stupid mistake :)

    – Jean-François Fabre
    Sep 14 '16 at 9:25











  • @Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

    – Lundin
    Sep 14 '16 at 9:27






  • 2





    I think can be better hosted on Documentation Beta.

    – LPs
    Sep 14 '16 at 9:27











  • @LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

    – Lundin
    Sep 14 '16 at 9:30













  • You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

    – Nik-Lz
    Mar 17 '17 at 11:53














16












16








16


3






This question is meant to be used as a canonical duplicate for this FAQ:



I am allocating data dynamically inside a function and everything works well, but only inside the function where the allocation takes place. When I attempt to use the same data outside the function, I get crashes or other unexpected program behavior.



Here is a MCVE:



#include <stdlib.h>
#include <stdio.h>

void create_array (int* data, int size)
{
data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);
}

void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("n");
}

int main (void)
{
int* data;
const int size = 5;

create_array(data, size);
print_array(data, size); // crash here

free(data);
}


Whenever print_array is called from inside the create_array function, I get the expected output 0 1 2 3 4, but when I call it from main, I get a program crash.



What is the reason for this?










share|improve this question
















This question is meant to be used as a canonical duplicate for this FAQ:



I am allocating data dynamically inside a function and everything works well, but only inside the function where the allocation takes place. When I attempt to use the same data outside the function, I get crashes or other unexpected program behavior.



Here is a MCVE:



#include <stdlib.h>
#include <stdio.h>

void create_array (int* data, int size)
{
data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);
}

void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("n");
}

int main (void)
{
int* data;
const int size = 5;

create_array(data, size);
print_array(data, size); // crash here

free(data);
}


Whenever print_array is called from inside the create_array function, I get the expected output 0 1 2 3 4, but when I call it from main, I get a program crash.



What is the reason for this?







c malloc parameter-passing dynamic-memory-allocation pass-by-value






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 23 at 12:05


























community wiki





5 revs, 2 users 99%
Lundin









  • 4





    I almost downvoted you for making such a stupid mistake :)

    – Jean-François Fabre
    Sep 14 '16 at 9:25











  • @Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

    – Lundin
    Sep 14 '16 at 9:27






  • 2





    I think can be better hosted on Documentation Beta.

    – LPs
    Sep 14 '16 at 9:27











  • @LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

    – Lundin
    Sep 14 '16 at 9:30













  • You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

    – Nik-Lz
    Mar 17 '17 at 11:53














  • 4





    I almost downvoted you for making such a stupid mistake :)

    – Jean-François Fabre
    Sep 14 '16 at 9:25











  • @Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

    – Lundin
    Sep 14 '16 at 9:27






  • 2





    I think can be better hosted on Documentation Beta.

    – LPs
    Sep 14 '16 at 9:27











  • @LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

    – Lundin
    Sep 14 '16 at 9:30













  • You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

    – Nik-Lz
    Mar 17 '17 at 11:53








4




4





I almost downvoted you for making such a stupid mistake :)

– Jean-François Fabre
Sep 14 '16 at 9:25





I almost downvoted you for making such a stupid mistake :)

– Jean-François Fabre
Sep 14 '16 at 9:25













@Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

– Lundin
Sep 14 '16 at 9:27





@Jean-FrançoisFabre Unfortunately I haven't found a way to make the question a community wiki, only the answer. I've poked the mods, so hopefully it will get converted to community wiki soon.

– Lundin
Sep 14 '16 at 9:27




2




2





I think can be better hosted on Documentation Beta.

– LPs
Sep 14 '16 at 9:27





I think can be better hosted on Documentation Beta.

– LPs
Sep 14 '16 at 9:27













@LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

– Lundin
Sep 14 '16 at 9:30







@LPs By all means, feel free to copy/pasta it over there. You can't use a Documentation page for close-as-duplicate though. Nor will it pop up when people post a new question nor search for the answer themselves.

– Lundin
Sep 14 '16 at 9:30















You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

– Nik-Lz
Mar 17 '17 at 11:53





You should have initialized data before using it, with create_array function. Otherwise an "uninitialized local variable data is being used" exception will be thrown.

– Nik-Lz
Mar 17 '17 at 11:53












1 Answer
1






active

oldest

votes


















13














The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.





Consider this simple example:



void func (int x)
{
x = 1;
printf("%d", x);
}

...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage


Here, a copy of the variable a is stored locally inside the function, as the parameter x. This is known as pass-by-value.



When x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.





Pointers are no exception to this pass-by-value rule. In your example, the pointer variable data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.



So the pointer variable in the caller remains uninitialized and therefore the program crashes. In addition, the create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.





There are two ways you can modify the function to work as expected. Either by returning a copy of the local variable back to the caller:



int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);

return data;
}

int main (void)
{
int* data;
const int size = 5;

data = create_array(size);
print_array(data, size);
}


or by passing the address to the caller's pointer variable and write directly to the caller variable:



void create_array (int** data, int size)
{
int* tmp = malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
{
tmp[i] = i;
}

*data = tmp;
print_array(*data, size);
}

int main (void)
{
int* data;
const int size = 5;

create_array(&data, size);
print_array(data, size);
}


Either form is fine.






share|improve this answer


























  • Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

    – Nik-Lz
    Mar 17 '17 at 12:20











  • @RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

    – Lundin
    Mar 17 '17 at 12:50













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%2f39486797%2fdynamic-memory-access-only-works-inside-function%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









13














The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.





Consider this simple example:



void func (int x)
{
x = 1;
printf("%d", x);
}

...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage


Here, a copy of the variable a is stored locally inside the function, as the parameter x. This is known as pass-by-value.



When x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.





Pointers are no exception to this pass-by-value rule. In your example, the pointer variable data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.



So the pointer variable in the caller remains uninitialized and therefore the program crashes. In addition, the create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.





There are two ways you can modify the function to work as expected. Either by returning a copy of the local variable back to the caller:



int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);

return data;
}

int main (void)
{
int* data;
const int size = 5;

data = create_array(size);
print_array(data, size);
}


or by passing the address to the caller's pointer variable and write directly to the caller variable:



void create_array (int** data, int size)
{
int* tmp = malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
{
tmp[i] = i;
}

*data = tmp;
print_array(*data, size);
}

int main (void)
{
int* data;
const int size = 5;

create_array(&data, size);
print_array(data, size);
}


Either form is fine.






share|improve this answer


























  • Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

    – Nik-Lz
    Mar 17 '17 at 12:20











  • @RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

    – Lundin
    Mar 17 '17 at 12:50


















13














The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.





Consider this simple example:



void func (int x)
{
x = 1;
printf("%d", x);
}

...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage


Here, a copy of the variable a is stored locally inside the function, as the parameter x. This is known as pass-by-value.



When x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.





Pointers are no exception to this pass-by-value rule. In your example, the pointer variable data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.



So the pointer variable in the caller remains uninitialized and therefore the program crashes. In addition, the create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.





There are two ways you can modify the function to work as expected. Either by returning a copy of the local variable back to the caller:



int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);

return data;
}

int main (void)
{
int* data;
const int size = 5;

data = create_array(size);
print_array(data, size);
}


or by passing the address to the caller's pointer variable and write directly to the caller variable:



void create_array (int** data, int size)
{
int* tmp = malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
{
tmp[i] = i;
}

*data = tmp;
print_array(*data, size);
}

int main (void)
{
int* data;
const int size = 5;

create_array(&data, size);
print_array(data, size);
}


Either form is fine.






share|improve this answer


























  • Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

    – Nik-Lz
    Mar 17 '17 at 12:20











  • @RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

    – Lundin
    Mar 17 '17 at 12:50
















13












13








13







The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.





Consider this simple example:



void func (int x)
{
x = 1;
printf("%d", x);
}

...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage


Here, a copy of the variable a is stored locally inside the function, as the parameter x. This is known as pass-by-value.



When x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.





Pointers are no exception to this pass-by-value rule. In your example, the pointer variable data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.



So the pointer variable in the caller remains uninitialized and therefore the program crashes. In addition, the create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.





There are two ways you can modify the function to work as expected. Either by returning a copy of the local variable back to the caller:



int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);

return data;
}

int main (void)
{
int* data;
const int size = 5;

data = create_array(size);
print_array(data, size);
}


or by passing the address to the caller's pointer variable and write directly to the caller variable:



void create_array (int** data, int size)
{
int* tmp = malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
{
tmp[i] = i;
}

*data = tmp;
print_array(*data, size);
}

int main (void)
{
int* data;
const int size = 5;

create_array(&data, size);
print_array(data, size);
}


Either form is fine.






share|improve this answer















The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.





Consider this simple example:



void func (int x)
{
x = 1;
printf("%d", x);
}

...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage


Here, a copy of the variable a is stored locally inside the function, as the parameter x. This is known as pass-by-value.



When x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.





Pointers are no exception to this pass-by-value rule. In your example, the pointer variable data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.



So the pointer variable in the caller remains uninitialized and therefore the program crashes. In addition, the create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.





There are two ways you can modify the function to work as expected. Either by returning a copy of the local variable back to the caller:



int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}

print_array(data, size);

return data;
}

int main (void)
{
int* data;
const int size = 5;

data = create_array(size);
print_array(data, size);
}


or by passing the address to the caller's pointer variable and write directly to the caller variable:



void create_array (int** data, int size)
{
int* tmp = malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
{
tmp[i] = i;
}

*data = tmp;
print_array(*data, size);
}

int main (void)
{
int* data;
const int size = 5;

create_array(&data, size);
print_array(data, size);
}


Either form is fine.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 '17 at 12:23


























community wiki





3 revs, 2 users 87%
Lundin














  • Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

    – Nik-Lz
    Mar 17 '17 at 12:20











  • @RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

    – Lundin
    Mar 17 '17 at 12:50





















  • Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

    – Nik-Lz
    Mar 17 '17 at 12:20











  • @RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

    – Lundin
    Mar 17 '17 at 12:50



















Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

– Nik-Lz
Mar 17 '17 at 12:20





Very good question and answer. You say that the pointer variable is passed by value, which is interesting, since being a pointer it contains an address. You have made a mistake in your second function, it should be print_array(tmp, size); *data = tmp. Or you can instead write: *data = tmp; printArray(*data, size);

– Nik-Lz
Mar 17 '17 at 12:20













@RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

– Lundin
Mar 17 '17 at 12:50







@RestlessC0bra Thanks, it's been fixed. Though this is a community wiki so you are free to edit it too.

– Lundin
Mar 17 '17 at 12:50






















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%2f39486797%2fdynamic-memory-access-only-works-inside-function%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

Bressuire

Vorschmack

Quarantine