My experience on my daily works... helping others ease each other

Tuesday, November 2, 2010

Simple C Programs with Buffer Overflow

As I'm learning to understand about buffer overflow, I wrote a simple code to test it out. From normal reading, code review, and even using static analysis tool to find out, none of it managed to capture this.
I might be wrong or using outdated tool. But if you guys can figure out what is the problem, then the tool I'm using is useless.
Here is the code:
#include
#include

void analyze_one_file(){
     char fileName[50] = "";
     char c = ' ';
     int i = 0;
    
     printf ("\n Analyzing One File......");
     fflush(stdout);
     fflush(stdin);
     printf ("\n Please enter the file name: ");

     for (i = 0; (i < sizeof(fileName) - 1 && (c = getchar()) !=EOF); i++){
         fileName[i] = c;        
     }

     /* another option tried
     for (i = 0; (i < sizeof(fileName) - 1 || (c = getchar()) !=EOF); i++){
         fileName[i] = c;        
     }*/
     /* another option tried
        while (i < sizeof(fileName) - 1 && c !=EOF){ //(c != '\n' || c != '\r')){
        c = getchar();
        //scanf("%c", &c);    
        if ( i < sizeof(fileName) - 1) {
          fileName[i] = c;
        }
        i++;       
     }*/
     printf ("\nFile Name: %s (i=%d)\n", fileName, i);
     system("PAUSE");
}
Share:

2 comments:

Unknown said...

for (i = 0; (i < sizeof(fileName) - 1 && (c = getchar()) !=EOF); i++){
fileName[i] = c;
}

/* string must be terminated */
fileName[i] = '\0';

masteramuk said...

Thanks luca....

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates