[英]strcpy cause Program received signal SIGSEGV, Segmentation fault
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:当我在 gdb 中调试它时,运行第一个 strcpy 是可以的,但是当它转到第二个 strcpy 时,它总是出现以下错误:
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?
有人知道吗?
Assuming you're using C-style strings for a reason - if not, just use std::string as @manni66 suggested above.假设您出于某种原因使用 C 风格的字符串 - 如果没有,只需使用 std::string 作为上面建议的@manni66。
You're declaring your variables SourceWeightFiel
and TargetWeightFiel
but you're not allocating any space to copy them into.您正在声明变量
SourceWeightFiel
和TargetWeightFiel
但没有分配任何空间来将它们复制到其中。 You can either do it yourself with malloc ()
(or similar) or use strdup ()
您可以使用
malloc ()
(或类似的)或使用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;
}
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.根本问题是 strcpy 不分配任何内存,它只是从一个地方复制到另一个地方,并假设在目标位置分配了足够的空间。
You need to allocate enough space in SourceWeightFiel and TargetWeightFile.您需要在 SourceWeightFiel 和 TargetWeightFile 中分配足够的空间。
Or even better, use strdup.或者甚至更好,使用 strdup。
As already mentioned, std::string will also simplify matters.如前所述, std::string 也将简化问题。
Another solution:另一种解决方案:
int main(int argc,char * argv[] )
{
char SourceWeightFiel[256]="";
char TargetWeightFile[256]="";
strcpy( SourceWeightFiel, argv[1] );
strcpy( TargetWeightFile, argv[2] );
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.