Exaequet Exaequet -4 years ago 54
C Question

Can't find the memory leak in C program

I am trying to write my first project in C and have some problems with the memory leak. I can't find the mistake, but I assume something's wrong with the do-while loop. The program compiles, but when I try to open it, I get a segmentation fault error. What am I doing wrong?

The file I am opening in my program is a .txt with the sequence of chars, for example: dvorndvl.

My aim is: I open the program with argument, it opens the file named argv[1] and writes the sequence of chars from the file to the array.

Here's my code:


void bye(){
puts("See you!");

int main(int argc, char *argv[]) {
char a[30];
int i, x;

printf("-----SOME TEXT-----");

FILE *f;
f = fopen(argv[1], "r");

if (f = NULL) {
printf("User doesn't exist.\n");
a[i] = getc(f);
} while(a[i]!=EOF);

char b[30];
printf("Password? ");
scanf("%c", b);

if(strcmp(a,b) == 0){
printf("\nHi, %s!\n", argv[1]);
printf("What do you want to do?");
printf("1. Turn the devices on/off. \n");
printf("2. Change my password. \n");
printf("3. -EXIT-\n");

switch(x) {
case 1:
devices(); break; //in file1
case 2:
encrypt(argv[1]); break;//in file2
case 3:
atexit(bye); break;
printf("Password is incorrect\n");
return 0;

Answer Source

A couple of things are wrong here:

 if (f = NULL) {

You are changing f to be NULL, not testing it against NULL. Use ==. To prevent this kind of error in the future, put the r-value on the left hand side, like so:

 NULL == f


char b[30];
scanf("%c", b);

If you were going to use scanf to read the string, you need to use %s format specifier, not %c, which is for single characters. I'd not use scanf at all though; use fgets instead because it's safer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download