使用时,strcpy的分段故障? [英] Segmentation fault when using strcpy?

查看:149
本文介绍了使用时,strcpy的分段故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过传递来定义在编译时的路径:

  -DDCROOTDEF =/路径/要/东西

在编译行。然后我试图让使用在code,如:

 的char * ptr_path;
的strcpy(ptr_path,DCROOTDEF);
strcat的(ptr_path,/ MainCommons / CommonLib /字体/ ARIAL.TTF);
字符* pftf = ptr_path;
gdImageStringFT(PIMG,brect,ICLR,pftf,PTS,陈子昂,IXP,国际马铃薯年,(字符*)CBUF);

这给了我一个分段错误。但是,如果我尝试先打印字符串:

 的char * ptr_path;
的strcpy(ptr_path,DCROOTDEF);
strcat的(ptr_path,/ MainCommons / CommonLib /字体/ ARIAL.TTF);
字符* pftf = ptr_path;
的printf(%S \\ n,pftf);
gdImageStringFT(PIMG,brect,ICLR,pftf,PTS,陈子昂,IXP,国际马铃薯年,(字符*)CBUF);

它工作得很好。我错过了什么复杂字符指针的是这里?

感谢


解决方案

 的char * ptr_path;
的strcpy(ptr_path,DCROOTDEF);

您从未初始化 ptr_path

它不会在第二code段工作,您是刚开始不走运,它的出现的工作。你还在使用未初始化的指针,并试图写谁在内存中知道了。

您需要初始化 ptr_path 来指向字符的数组至少的strlen(DCROOTDEF)+ 1 长。您还需要内容复制到阵列中,以确保它不会太长前检查 DCROOTDEF 的长度。您可以手动使用的strlen ,也可以使用像一个长度检查拷贝功能 strlcpy

I'm trying to define a path at compile time by passing:

-DDCROOTDEF='"/path/to/stuff"'

on the compile line. I then try to get use this in the code like:

char * ptr_path;  
strcpy(ptr_path, DCROOTDEF);
strcat(ptr_path,"/MainCommons/CommonLib/fonts/Arial.ttf");
char *pftf=ptr_path;
gdImageStringFT(pimg,brect,iclr,pftf,pts,ang,ixp,iyp, (char *)cbuf);

Which gives me a segmentation fault. However, if I try to print the string first:

char * ptr_path;
strcpy(ptr_path, DCROOTDEF);
strcat(ptr_path,"/MainCommons/CommonLib/fonts/Arial.ttf");
char *pftf=ptr_path;
printf("%s\n",pftf);
gdImageStringFT(pimg,brect,iclr,pftf,pts,ang,ixp,iyp, (char *)cbuf);

It works just fine. What intricacy of char pointer's am I missing here?

Thanks

解决方案

char * ptr_path;
strcpy(ptr_path, DCROOTDEF);

You never initialize ptr_path.

It doesn't work in the second code snippet, you are just getting unlucky and it appears to work. You're still using an uninitialized pointer and trying to write to who knows where in memory.

You need to initialize ptr_path to point to an array of char that is at least strlen(DCROOTDEF) + 1 in length. You also need to check the length of DCROOTDEF before copying its contents into the array to be sure that it is not too long. You can do so manually using strlen or you can use a length-checked copy function like strlcpy.

这篇关于使用时,strcpy的分段故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆