#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
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()
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)"
"realloc(
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
Reason: realloc(
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=0The memory space allocated by malloc is uninitialized, so mp has some garbage value. calloc initilize the allocated memory space to zero. so cp=0
cp=0The 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);
}
- free() fails
- strcpy() fails
- prints I LOVE C
- error
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;
}
- Compilation Error
- Runtime Error
- Will give a warning,but run anyway
- neither warning nor error
3.Will give a warning,but run anyway
The starting address is 14311440
The starting address is 14311440
in question no. 6 casting should ne done
ReplyDeleteHello, I do not agree with the previous commentator - not so simple
ReplyDeleteQuestion no 2 is working fine Turbo C++ and DEV C++
ReplyDeleteQuestion no 4 is working fine Turbo C++ and DEV C++
Output of Question No 7 is 0 in turbo c++