Wednesday, September 28, 2005

Catch 'em, Kill 'em Pt.2 - Kill 'em

After the overwhelming response of all the code warriors out there, I decided to put the answers up. I could have provided alternate answers, but I just chose to provide the ones that the author provided.

the original posts can be found at Michael Howard's Web Log

// Example #1 (code prior to this verifies pszSrc is <= 50 chars) #define MAX (50) char *pszDest = malloc(sizeof(pszSrc)); strncpy(pszDest,pszSrc,MAX); The code is allocating the size of a pointer, 4-bytes on a 32-bit CPU, and then trying to copy 40 bytes.

// Example #2
#define MAX (50)
char szDest[MAX];
If the length of the string pointed to by pszSrc is exactly MAX, then strncpy does NOT null-terminate szDest.

// Example #3
#define MAX (50)
char szDest[MAX];
pszDest[MAX] = '\0';
Oooops - we just whacked element 51, not 50!

// Example #4
#define MAX (50)
char szDest[MAX];
The last arg to strncat is not the total length of szDest, it's how much space REMAINS!

// Example #5
char szDest[50];
_snprintf(szDest, strlen(szDest), "%s",szSrc);
szDest hasn't been initialized yet, so strlen(szDest) could return any value!

// Example #6
#define MAX (50)
void func(char *p) {
char szDest[MAX];
szDest[MAX-1] = '\0';
If p == NULL, your app just died!

No comments: