Thursday, June 10, 2010

Some C language Questions...

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

2. p=calloc(1,sizeof(int));
free(p);
p=realloc(p,sizeof(int));

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

3. p=calloc(1,sizeof(int));
free(p);
p=NULL;
p=realloc(p,sizeof(int));

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

4. 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);

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

5.int *mp,*cp;
mp=(int*)malloc(sizeof(int));
printf("mp=%d\n",*mp);
cp=(int*)calloc(sizeof(int),1);
printf("cp=%d\n",*cp);

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.
#include
void main()
{
char *pd,*ps="I LOVE C";
pd=malloc(strlen(ps));
strcpy(pd,ps);
printf("%s",pd);
free(pd);
}
prints I LOVE C

7. int *p;
p=(int *)malloc(-10);
printf("p=%d",*p);
free(p);
Segmentation Fault

8.
int *p;
p=(char *)malloc(sizeof(10));
printf("The starting address is %d\n",p);
return 0;
Will give a warning,but run anyway

ptr = (cast *)malloc(size) Malloc returns void * which is explicitly casted to cast *.

printf("%d\n", sizeof(++x));
x is not incremented since sizeof doesn't evaluate its operand.

long long a;
int b;
int c;
a = b + c;
then expecting that no matter how big b and c are that they won't overflow because a is big enough. But in reality the calculation is done by adding c in to b, which might overflow b. The value of b is then assigned to a.
Using a = (long long) b + c; yielded the correct result.


#define myCharPointer char*

int main(){
myCharPointer p1, p2;
...
}
That's one of the reasons you should use typedef instead of #define


//courtesy: stackexchange for programmers

No comments:

Post a Comment