[glug-t] Re: Hacking in C
- From: Vijay Kumar <vijaykumar@xxxxxxxxxxxx>
- To: glug_t@xxxxxxxxxxxxx
- Date: 05 Apr 2005 22:21:19 +0530
Aashish Ramdas <aashish_ramdas@xxxxxxxxx> writes:
> char *p = str1;
> while( *p++ = *str2++ );
> return str1;
This is what strcpy does.
> Of course, all this is assuming that str1 is pointing to some valid
> memory, and is adequate...
The problem is that you cannot _always_ assume that the buffer is
sufficient... Programmers new to C, forget that such an assumption
exists.
Now what if we cannot make such an assumption? A quick look at the man
page would suggest strncpy. But it is not as simple as replacing
strcpy with strncpy. When the source string is larger than the
destination buffer, the copied string is _not_ terminated with '\0'!
You will have to write
strcpy (dest, src, BUF_SIZE);
dest[BUF_SIZE-1] = '\0';
A much simpler way to do this is to use snprintf(not sprintf!). It
properly terminates the string, even if the source string is
longer. Some would end up writing
snprintf (dest, BUF_SIZE, src);
But this is incorrect as well. If the src string contains "%", hell
will break loose. It should have been written as
snprintf (dest, BUF_SIZE, "%s", src);
Now there is another assumption in this piece of code. The assumption
that it is ok, if the string gets truncated. This assumption is not
always true as well. If you cannot make this assumption you will have
to write something like this
buf = malloc(strlen(src)+1);
if (buf == NULL)
/* take necessary action */
strcpy(buf, src);
You can do this is in a single step using strdup, or asprintf.
With this you have the additional overhead of having to free the
buffer and to check for memory allocation failures.
Phew! Well it is not always that complex. It is all about knowing what
assumptions you _can_ make and what you cannot.
I hope I have pointed some gotchas in the C language. Feel free to
send in similar gotchas. Do let me know, if I have gone wrong
somewhere.
I hope this will help people to write better free software.
Regards,
Vijay
---------------------------------------------------------------
To unsubscribe send a mail to glug_t-request@xxxxxxxxxxxxx with
'unsubscribe' as subject.
Website: http://glugt.linuxisle.com
- References:
- [glug-t] Re: Hacking in C
- From: Aashish Ramdas
Other related posts:
- » [glug-t] Hacking in C
- » [glug-t] Re: Hacking in C
- » [glug-t] Re: Hacking in C
- » [glug-t] Re: Hacking in C
- [glug-t] Re: Hacking in C
- From: Aashish Ramdas