Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What programming errors is this page highlighting?

Tags:

c

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

like image 655
Carson Myers Avatar asked Dec 23 '22 09:12

Carson Myers


2 Answers

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.

like image 80
newacct Avatar answered Jan 09 '23 08:01

newacct


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

like image 28
AProgrammer Avatar answered Jan 09 '23 10:01

AProgrammer