arrays - C Dynamic Memory vs Stack Memory Variables -


when c array created using malloc, array stored in heap, , when c array created statically stored in stack. however, happens if return element of c array initialized statically function? wording may strange, here 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 staticelement in memory? staticarray cleared off stack because function has finished, or still on stack because , element of staticarray has been returned?
note: know did not free dynamic array, , leaking memory, example , not meant used.

in c, if return char or int function, you're returning copy of value function, not actual object itself. in other words, if return element of array declared local variable, you're returning copy of array element, when original array destroyed there's no worry somehow "lose" array element. similarly, if return element of array allocated malloc, you're returning copy of array element rather element itself. why you're not getting garbage values in above code.

the value that's handed not stored in either stack or heap. it's stored in register somewhere. language's point of view has automatic storage duration , cleaned automatically. since you're storing value in local variable, stored on stack (or, more technically, has automatic storage duration), that's because put in local variable , has nothing fact in dynamically- or statically-allocated array.

that said, are leaking memory, since never free data allocated malloc.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -