by : ev1lut10n (A Chinese Man lives in Indonesia)
'Even experienced programmers still makes bug because he's human'
There are some c programming bugs, here are some of them
[Double Free Bug]
this double free bug happens when we calle free more than once after we
use a memory allocation
(if u calle more than 2 free this is gonna buffer overflow)
ex of wrong code:
============
/**made by ev1lut10n**/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[])
{
if (fork()!= 0)
{
exit(1);
}
fprintf(stdout,"\nYour argument is %s",argv[1]);
char *bufer = (char *)malloc(sizeof(argv[1]));
fprintf(stdout,"\nWe make first free after this\n");
free(bufer);
fprintf(stdout,"\nWe make our second free after this caused double
free\n");
free(bufer);
return(0);
}
==============
from the above c code we see the programmer free the buffer more than once
after malloc:
char *bufer = (char *)malloc(sizeof(argv[1])); ---------- here he use
malloc to allocate heap
after that he use free(bufer); and below he use it once again free(bufer);
even experienced C programmers sometimes still makes this mistake
GNU C Library heap protector
===============
root@mywisdom-Vostro1310:/home/mywisdom/www/artikel/bugs# ./df
Your argument is (null)
We make first free after this
example of correct C code:
========
/**made by ev1lut10n**/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[])
{
if (fork()!= 0)
{
exit(1);
}
fprintf(stdout,"\nYour argument is %s",argv[1]);
char *bufer = (char *)malloc(sizeof(argv[1]));
fprintf(stdout,"\nWe make first free after this\n");
free(bufer);
return(0);
}
=============
[Dangling Pointers]
This happens when we delete an object from memory, the associated pointer
still points to the memory address of that object
sample of dangling pointer (taken from internet)
===========
#include<stdio.h>
int *call();
void main()
{
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call()
{
int x=25;
++x;
return &x;
}
==============
from the above sample we create a pointer
int *ptr;
then the &pointer is filled by return value of function: call()
then it's followed by fflush(stdin), as we know fflush return value is 0
this is just the same as ptr=NULL;
after that the ptr becomes dangling pointer and shouldnt be used for next
code, unfortunetly
it's followed by : printf("%d",*ptr);
it becomes a dangling pointer buggy code.
the correct one should be without fflush
===========
#include<stdio.h>
int *call();
void main()
{
int *ptr;
ptr=call();
printf("%d",*ptr);
}
int * call()
{
int x=25;
++x;
return &x;
}
==============