The greatest mistake you can make in life is to be continually fearing you will make one

Wednesday 17 March 2010

C Question of the Day -malloc(),calloc(),realloc(),free()

1. Will this result in any runtime error?
#include <stdlib.h>
main()
{
int p;
p=calloc(1,sizeof(int));
free(p);
p=NULL;
free(p);
}   
Solution

No
Freeing a null pointer wont result in any error; The free() call would return without doing anything


2. Will this result in any runtime error?
#include <stdlib.h>
main()
{
int *p;
p=calloc(1,sizeof(int));
free(p);
p=realloc(p,sizeof(int));
}
Solution

Yes Error: "glibc detected ** ... : double free or corruption"
Reason: "realloc(ptr,size)" has to be invoked after (m|c)alloc(), but before free()


3. Will this result in any runtime error?

#include <stdlib.h>
main()
{
int p;
p=calloc(1,sizeof(int));
free(p);
p=NULL;
p=realloc(p,sizeof(int));
}
Solution

No
"realloc(,size)" is equivalent to "malloc(size)"

4. Will this result in any runtime error?

#include <stdlib.h>
main()
{
int *p;
p=calloc(1,sizeof(int));
free(p);
p=realloc(p, 0 * sizeof(int));
p=NULL;
p=realloc(p, 1 * sizeof(int));
*p=1;
free(p);
}
Solution

Yes. Error: "glibc detected ** ... : double free or corruption"
Reason: realloc(,0) is equivalent to free(); So we end up with double free


5.What is the output of the following program?
#include<stdio.h>
void main()
{
    int *mp,*cp;
    mp=(int*)malloc(sizeof(int));
    printf("mp=%d\n",*mp);
    cp=(int*)calloc(sizeof(int),1);
    printf("cp=%d\n",*cp);
}
Solution

mp=garbage value
cp=0
The memory space allocated by malloc is uninitialized, so mp has some garbage value. calloc initilize the allocated memory space to zero. so cp=0


6.What is the output of the following program?
#include<stdio.h>
void main()
{
    char *pd,*ps="I LOVE C";
    pd=malloc(strlen(ps));
    strcpy(pd,ps);
    printf("%s",pd);
    free(pd);
}
  1. free() fails
  2. strcpy() fails
  3. prints I LOVE C
  4. error
Solution

3.prints I LOVE C


7.What is the output of the following program?
#include<stdio.h>
void main()
{
    int *p;
    p=(int *)malloc(-10);
    printf("p=%d",*p);
    free(p);
}
Solution

Segmentation Fault


8.What is the output of the following program?
#include<stdio.h>
int main()
{
    int *p;
    p=(char *)malloc(sizeof(10));
    printf("The starting address is %d\n",p);
    return 0;
}
  1. Compilation Error
  2. Runtime Error
  3. Will give a warning,but run anyway
  4. neither warning nor error
Solution

3.Will give a warning,but run anyway
The starting address is 14311440

3 comments:

  1. in question no. 6 casting should ne done

    ReplyDelete
  2. Hello, I do not agree with the previous commentator - not so simple

    ReplyDelete
  3. Question no 2 is working fine Turbo C++ and DEV C++
    Question no 4 is working fine Turbo C++ and DEV C++
    Output of Question No 7 is 0 in turbo c++

    ReplyDelete