Ok, so I took a little longer than expected to post the answers, but here they are. BTW, many people worked them out :)
// 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];strncpy(szDest,pszSrc,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];strncpy(szDest,pszSrc,MAX);pszDest[MAX] = '\0';Oooops - we just whacked element 51, not 50!
// Example #4#define MAX (50)char szDest[MAX];strncpy(szDest,pszSrc,MAX-1);strncat(szDest,pszSrc,MAX-1);The last arg to strncat is not the total length of szDest, it's how much space REMAINS!
// Example #5char 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]; strncpy(szDest,p,MAX); szDest[MAX-1] = '\0';}If p == NULL, you're app just died!