The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+1 vote
162 views
can anyone tell broadly about "Arbitrary lifetime in case of heap allocation".
asked in Compiler Design by (269 points) | 162 views

2 Answers

+1 vote
Malloc, calloc are primary examples of heap allocation. Once we have assigned a memory using these functions then it is upon us, the programmer, when we free them them using "free" and thus the word arbitrary. This is the reason why heap is dynamic memory allocation.
answered by Active (5.2k points)
0 votes

Lifetime cannot be arbitrary. Allocation in Data, BSS remains till the end of the program. Allocation in the heap remains until the program break is moved or that memory is reallocated. Same for the stack.

Consider the following example

int func(int n)
{
   int x = n;
   return x+x;
}

int main()
{
   int x = 5;
   x = func(x);
   long* ptr = &x;
   printf("Argument : %ld\n", *ptr);
   printf("Return Address: %p\n", ptr[-3]);
}

When compiled under  gcc-7 (Ubuntu 7.3.0-16ubuntu3) 7.3.0, gives the output

Argument : 10
Return Address: 0x80484db

Where the return address represents the address at which the execution resumes after returing from func.

answered by (329 points)

Related questions

+1 vote
0 answers
6
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,047 questions
53,187 answers
184,496 comments
70,394 users