-5

I have the following codes:

int main(int argc,char * argv[] )
{

  char* SourceWeightFiel;

  char* TargetWeightFile;

   strcpy( SourceWeightFiel, argv[1] );

   strcpy( TargetWeightFile, argv[2] );

 return 1;
}

when I debug it in gdb, it's Ok in running the first strcpy, but when it goes to the second strcpy, it always gives the following errors:

26     strcpy( SourceWeightFiel, argv[1] );   
(gdb) n     
27     strcpy( TargetWeightFile, args );    
(gdb) n

Program received signal SIGSEGV, Segmentation fault.    
__strcpy_sse2_unaligned ()
    at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:94    
94  ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or directory.    
(gdb)

I cannot figure out why, and have no idea how to fix it. Does anyone know about it?

greenleaf
  • 791
  • 1
  • 7
  • 11
  • 3
    These statements strcpy( SourceWeightFiel, argv[1] ); strcpy( TargetWeightFile, argv[2] ); do not make sense and have undefined behavior because the pointers are not initialized anfd have indeterminate values – Vlad from Moscow Oct 27 '17 at 14:11
  • It's C++. Use std::string and not strcpy. –  Oct 27 '17 at 14:12
  • You do not test if argv[1] or argv[2] exist. –  Oct 27 '17 at 14:13

3 Answers3

0

Assuming you're using C-style strings for a reason - if not, just use std::string as @manni66 suggested above.

You're declaring your variables SourceWeightFiel and TargetWeightFiel but you're not allocating any space to copy them into. You can either do it yourself with malloc () (or similar) or use strdup ()

Don't forget to free that allocated space (whichever method you use) once you're done with it.

int main(int argc,char * argv[] ) {

    char* SourceWeightFiel;
    char* TargetWeightFile;

    SourceWeightFiel = strdup (argv[1]);
    TargetWeightFile = strdup (argv[2]);

    /* After you've used them... */

    free (TargetWeightFile);
    free (SourceWeightFiel);
    return 1;
}
Steve
  • 1,747
  • 10
  • 18
0

The fundamental problem is that strcpy does not allocate any memory, it just copies from one place to another and assumes that enough space is allocated at the destination location.

You need to allocate enough space in SourceWeightFiel and TargetWeightFile.

Or even better, use strdup.

As already mentioned, std::string will also simplify matters.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
0

Another solution:

int main(int argc,char * argv[] )
{
  char SourceWeightFiel[256]="";
  char TargetWeightFile[256]="";

  strcpy( SourceWeightFiel, argv[1] );
  strcpy( TargetWeightFile, argv[2] );

 return 1;
}
greenleaf
  • 791
  • 1
  • 7
  • 11