Search code examples
cscopeinitializationdynamic-memory-allocationlifetime

are heap variables global variables and what is the scope and lifetime of heap variables


#include<stdio.h>
#include<conio.h>
#include<alloc.h>

int * makearray(int );
void readdata(int *,int );
void printdata(int *,int );

void main()
{
    int *a,num;
    clrscr();
    printf("enter the size of array\n");
    scanf("%d",&num);
    a=makearray(num);
    readdata(temp,num);
    printdata(a,num);
    getch();
}

int * makearray(int n)
{
    int *temp;
    temp=(int *)malloc(sizeof(int)*n);
    printf("address of temp is %x and value of temp is %d and first value of            temp is garbage i.e %d\n",&temp,temp,*temp);
    return temp;
}

void readdata(int *x,int n)
{
    for(n--; n>=0; n--)
    {
        printf("enter the value in cell[%d]\n",n);
        scanf("%d",x+n);
    }
    return;
}

void printdata(int *x,int n)
{
    for(n--; n>=0; n--)
        printf("the value in cell[%d] is %d",n,*(x+n));
    return;
}

in the following code I want to know since the scope of heap variables if for the duration of the program why is temp shown as unidentified symbol in the program?

Also I want to know what is the lifetime and scope of the heap variables.

Also I want to know that since a variable is reserved a space in memory only when it is initialized when we return the pointer temp a is initialized but what happens to temp after that ? Does it remain initialized or it is freed.


Solution

  • I think you're mixing up two concepts, scope and lifetime.

    Quoting C11, chapter §6.2.1

    For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. [...]

    and

    The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime. [....]

    The problem here is, the identifier temp has a block scope of function makearray(). The value held by temp (a pointer) is returned by a memory allocator functions and thus obviously it has a liferime until it's deallocated but that does not mean the temp variable itself has a file scope.

    You have used another variable a to store the return value of makearray(), so use that.