C language

Q5: Memory allocation

int main()
{
  int*x;
  x = abc();
  printf(“%d”,*x);
  return 0;
}

int* abc()
{
  int y=3;
  return (&y);
}

As address of the variable y is returned and which gets stored in x and the memory block of function abc() is de-allocated.

www.exploreroots.com

Next we try to store a value in the memory which has been de-allocated. As memory has been de-allocated and hence operating system may have allocated this memory to some other process. Due to this reason referencing to this address may cause an ERROR and hence we better should mark the option of uncertain or can’t say.

SOLUTION: The solution to the above problem can be that if we declare a pointer in place of simple variable and return the address stored in the pointer as:

int* abc()
{
  int* y= malloc(sizeof(int));

  *y=3;
  return (&y);
}

Leave a Reply

Your email address will not be published. Required fields are marked *