On Tue, Sep 4, 2012 at 2:03 PM, Scott Ford <scott_j_f...@yahoo.com> wrote:

> I have had to move a string type field like a parameter to a field like
> this,
>
> Jobn   char[40];
>
> memset(Jobn,'0',sizeof(Jobn));
> strcpy(Jobn,xxxxx);
>
> Otherwise strcmp fails, where xxxxx is the parameter string
>
>
>
"fails" how?

the memset() has no effect other than to zero out the data after the string
terminator.

The conventional safe way is:

strncpy(Jobn, xxxxx, sizeof(Jobn)-1);
Jobn[sizeof(Jobn)-1] = '\0';   // ensure terminator in case strlen(xxxxx)
>= sizeof(Jobn)

(BTW - strncpy() also zeros bytes after the terminator, if necessary)

For more information, see: http://www.courtesan.com/todd/papers/strlcpy.html
under "Common Misconceptions"

Kirk Wolf
Dovetailed Technologies

PS> The above strncpy() idiom will truncate a source string longer than the
target.
If you want to instead raise an error:

strncpy(Jobn, xxxxx, sizeof(Jobn)-1);
if (Jobn[sizeof(Jobn)-1]) ...  // error if strlen(xxxxx) > sizeof(Jobn)-1

There's nothing z-unique here... standard pitfalls and practices of using C
that apply anywhere

----------------------------------------------------------------------
For IBM-MAIN subscribe / signoff / archive access instructions,
send email to lists...@listserv.ua.edu with the message: INFO IBM-MAIN

Reply via email to