I\'m trying to get rid of some compiler warnings that say strcpy, sprintf, etc are unsafe. I get why they\'re unsafe, but I can\'t think of a good way to fix the code, in a
You do know how much to copy - you allocated space for it!
Surely you wouldn't willingly copy more than the space you allocated?
I would prefer to use a method that explicitly avoids buffer overruns by limiting the number of items copied. Back when I was a C programmer we used
dest = malloc(len); // note: where did we get len?
if ( dest is null ) panic! // note: malloc can fail
strncpy(dest, src, len);
dest[len-1] =0;
This is slightly messy, and has been pointed out is using strncpy() a method which really was originally designed for fixed-width fields rather than strings. However it does ach
There are methods such as strdup() and strlcpy() which may we help.
My recommendations:
1). Your target should not be to suppress warnings but to make the code robust.
2). When copying strings you need to ensure these things:
If strlcpy() is available in your environment then you could use it, otherwise why not write your own little utilityy function? Then if there are warnings in just that function you've localised then problem.