Advertisement

12.03.2004 at 04:17AM PST, ID: 21229045
[x]
Attachment Details

Memory allocation Stack Or Heap??

Asked by madhurdixit in C Programming Language

Tags: c, stack, memory, heap, allocation

We have a code as below:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
main()
{
  char *i;
 const char ch = 'a';
 strcpy(i,&ch);
 printf("%lx %lx %c",sbrk(0),i , *i);
}

This program throws segemtation fault. But when strcpy is replaced by " *i = ch; " , this one works.
As we understand, for local variables we get a memory in stack as long as we dont do
malloc . But then simple assignment should also fail because "i" hasnt been allocated any memory before assignment.
How exactly a memory is allocated in this case.

As we see in printf , sbrk gives us the end of heap address. This value turns out to be more than i's value. If stack is allocated in higher memory address than heap , then this shows that i refers to a memory in heap and not in stack.

Please throw some light on this.Start Free Trial
 
 
[+][-]12.03.2004 at 04:37AM PST, ID: 12735320

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: C Programming Language
Tags: c, stack, memory, heap, allocation
Sign Up Now!
Solution Provided By: ddunlea
Participating Experts: 3
Solution Grade: B
 
 
[+][-]12.03.2004 at 06:18AM PST, ID: 12736104

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]12.04.2004 at 05:59AM PST, ID: 12744136

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32