1

I am trying to write a program that could read/write the rolodex info (the file will be named myRolodex by default). But I think the line: strcpy(filename,"myRolodex"); causes Segmentation fault (core dumped) in my GCC compiler.

Any help to fix would be grateful!

#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include<stdbool.h>
int main(int argc, char* argv[]){
    char filename[250];
    if (argv[1]==NULL){
        strcpy(filename,"myRolodex");
    }
    strcpy(filename,argv[1]);
    printf("%s",filename);
    return 0;
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 1
    Add `else` before `strcpy(filename,argv[1]);`. Otherwise, this `strcpy` will execute even when `argv[1]` is `NULL`. – Spikatrix May 28 '15 at 09:03
  • @Cool Guy, the `strcpy` will only execute if `argv` is `NULL`. I think that is his intention, because he wants the name to be `"myRolodex"` by default, and this would be if `argv[1]` is equal `NULL`. But you are right on the second strcpy, there should be an else befor that. – Singularity May 28 '15 at 09:05
  • 2
    By the way, instead of checking if `argv[1]` is NULL, you better check if `argc < 2`. And for your problem, indeed you have to add an `else` statement. – Misery May 28 '15 at 09:07

1 Answers1

2

Correct your code as follows

if (argv[1]==NULL){
        strcpy(filename,"myRolodex");
    }else{
    strcpy(filename,argv[1]);
}

The problem is, even if you check argv[1]==NULL, statment strcpy(filename,argv[1]); will be always be executed since it's not in else block.

Sajith Eshan
  • 696
  • 4
  • 17