http://dspace.dial.pipex.com/town/green/gfd34/art/bloopers.html
The first one seems simple;
return strcpy(malloc(strlen(s)), s);
malloc
could return null
, and strcpy
could try to copy data to memory address 0. Or s could be a pointer to a string (rather than an array), and malloc
would only allocate enough space for a pointer, and would try and copy a string into it. (I think).
What about the second one though?
What a shame that he didn't cast ch to unsigned char when he wrote ch = toupper(ch);
Why should you cast ch
to unsigned char
if you write ch = toUpper(ch);
?
The first one seems simple; malloc could return null, and strcpy could try to copy data to memory address 0. Or s could be a pointer to a string (rather than an array), and malloc would only allocate enough space for a pointer, and would try and copy a string into it. (I think).
Simple enough, right? You missed the most obvious thing wrong with this: you are not allocating enough space. strcpy()
copies the string plus the terminating null byte, so the destination buffer must be size at least 1 bigger than the length of the string.
The toupper
function (with a lower case U) takes either the value of an unsigned char or EOF. If char is signed, passing a char to toupper() without converting it to an unsigned char first can pass other values with undefined behaviour. The implementation of toupper often look like this:
int toupper(int c)
{
return touppermap[c+1];
}
so the problem here is real. (This implementation assumes EOF is -1, which you can't formally do but nothing prevent the implementation to be knowledgeable about its own characteristics).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With