Turtle
Turtle

Reputation: 1389

C Dynamic Memory vs Stack Memory Variables

When a C array is created using malloc, the array is stored in the heap, and when a C array is created statically it is stored in the stack. However, what happens if you return an element of a C array initialized statically from a function? My wording may be strange, so here is an example:

#include <stdio.h>
#include <stdlib.h>
char getStaticElement();
char getDynamicElement();

int main() {
    char dynamicElement = getDynamicElement();
    char staticElement = getStaticElement();
    printf("Dynamic Element: %c\n", dynamicElement);
    printf("Static Element: %c\n", staticElement);
    return 0;

}
char getStaticElement() {
    char staticArray [] = {'a','b','c'};
    return staticArray[1]; // returns b
}
char getDynamicElement() {
    char * dynamicArray = malloc(sizeof(char)*4);
    dynamicArray [0] ='a';
    dynamicArray [1] ='b';
    dynamicArray [2] ='c';
    dynamicArray [3] ='\0';
    return dynamicArray[1]; // returns b
}

So where is staticElement in memory? Is staticArray cleared off the stack because the function has finished, or is it still on the Stack because and element of staticArray has been returned?
NOTE: I know I did not free dynamic array, and am leaking memory, this is just an example and not meant to be used.

Upvotes: 0

Views: 95

Answers (1)

templatetypedef
templatetypedef

Reputation: 372814

In C, if you return a char or int from a function, you're returning a copy of that value from the function, not the actual object itself. In other words, if you return an element of an array you declared as a local variable, you're really returning a copy of that array element, so even when the original array is destroyed there's no worry that you somehow "lose" that array element. Similarly, if you return an element of an array allocated with malloc, you're returning a copy of the array element rather than the element itself. This is why you're not getting garbage values back in the above code.

The value that's handed back is not necessarily stored in either the stack or the heap. It's usually stored in a register somewhere. From the language's point of view it has automatic storage duration and so will get cleaned up automatically. Since you're storing that value in a local variable, it will be stored on the stack (or, more technically, it has automatic storage duration), but that's because you put it in a local variable and has nothing to do with the fact that it was originally in a dynamically- or statically-allocated array.

That said, you are leaking memory, since you never free the data that you allocated with malloc.

Upvotes: 3

Related Questions