Reputation: 67
I'm trying to understand where memory is allocated in c programs.
void func1(char e, int f, int g)
{
int b = 4;
char * s = "hello world";
char * temp = (char *) malloc(15);
}
As I understand it, there are three automatic variables allocated on the stack b,s, and temp. where the contents of b (4) is stored on the stack, and the pointers s and temp are stored on the stack, and the data for temp is stored in the heap, but where is the data for s stored? because the b,s, and temp will be gone when we leave the func1 call but the memory for the contents has been allocated permanently. My other questions is the stack pointer always shifted down by 4 like when pushing the functions arguments on, even in the case of a char which is one byte? would the stack look like this, even though e is only one byte?
30:// other stuff
26: g
22: f
18: e
http://www.firmcodes.com/wp-content/uploads/2014/08/memory.png isnt this the layout for a c program?
Upvotes: 2
Views: 445
Reputation: 141638
In standard C terminology there are four possible storage durations:
b
)"Hello world"
)malloc(15)
)The other stuff you ask about in your question are properties of particular compilers and platforms. Some setups have no stack and no heap, no data segment or .data or .bss section, and so on.
Further reading:
Upvotes: 0
Reputation: 73424
It depends on your platform and it is implementation-defined. In general it goes to the read-only memory, if available on your system. Read more here.
As you noted, when the function terminated the automatic variables will be gone, causing a memory leak, but only for the case where you allocated memory dynamically!
That means that you have to let func1()
communicate temp
with its caller (e.g. main()
), so that you can later free()
it. Or if you don't need it after the function has done its job, then free()
it just before exiting the function.
By the way, as iharob said: Do I cast the result of malloc? NO!
As for your other question, which should be a new question, read this and this, they might help.
Upvotes: 1