Segmentation error when using strcpy?

I am trying to determine the path at compile time by passing:

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

on the compilation line. Then I try to use this in code, for example:

 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); 

This gives me a segmentation error. However, if I try to print the line 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 great. What complexity in char pointer do I not see here?

thanks

+2
source share
3 answers
 char * ptr_path; strcpy(ptr_path, DCROOTDEF); 

You never initialize ptr_path .

In the second code snippet, it doesn't work, you are just out of luck, and it seems to work. You are still using an uninitialized pointer and trying to write who knows where in memory.

You need to initialize ptr_path to specify a char array with a length of at least strlen(DCROOTDEF) + 1 . You should also check the length of DCROOTDEF before copying its contents to an array to make sure it is not too long. You can do this manually using strlen , or you can use a copy function with a length check like strlcpy .

+3
source

The ptr_path pointer ptr_path not initialized to point to writable memory, so it dereferences it with strcpy() .

You need to call, for example. malloc() to get a space, first:

 char * ptr_path = malloc(PATH_MAX); 

Or something like that.

+1
source

IN

 char * ptr_path; strcpy(ptr_path, DCROOTDEF); strcat(ptr_path,"/MainCommons/CommonLib/fonts/Arial.ttf"); 

the pointer is not tied to a legally allocated block of memory, so your program runs in undefined. First you need to allocate a buffer, for example using malloc() . Make sure the buffer is large enough to hold the resulting string along with the terminating null character.

+1
source

All Articles