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
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_pathto point to an array ofcharthat is at leaststrlen(DCROOTDEF) + 1in length. You also need to check the length ofDCROOTDEFbefore copying its contents into the array to be sure that it is not too long. You can do so manually usingstrlenor you can use a length-checked copy function likestrlcpy.