1112
Example 1:
Care should be taken to ensure sizeof returns the size of the data structure itself, and not the size
of the pointer to the data structure.
In this example, sizeof(foo) returns the size of the pointer.
Example Language: C (Bad)
double *foo;
...
foo = (double *)malloc(sizeof(foo));
In this example, sizeof(*foo) returns the size of the data structure and not the size of the pointer.
Example Language: C (Good)
double *foo;
...
foo = (double *)malloc(sizeof(*foo));
Example 2:
This example defines a fixed username and password. The AuthenticateUser() function is intended
to accept a username and a password from an untrusted user, and check to ensure that it matches
the username and password. If the username and password match, AuthenticateUser() is intended
to indicate that authentication succeeded.
Example Language: (Bad)
/* Ignore CWE-259 (hard-coded password) and CWE-309 (use of password system for authentication) for this example. */
char *username = "admin";
char *pass = "password";
int AuthenticateUser(char *inUser, char *inPass) {
printf("Sizeof username = %d\n", sizeof(username));
printf("Sizeof pass = %d\n", sizeof(pass));
if (strncmp(username, inUser, sizeof(username))) {
printf("Auth failure of username using sizeof\n");
return(AUTH_FAIL);
}
/* Because of CWE-467, the sizeof returns 4 on many platforms and architectures. */
if (! strncmp(pass, inPass, sizeof(pass))) {
printf("Auth success of password using sizeof\n");
return(AUTH_SUCCESS);
}
else {
printf("Auth fail of password using sizeof\n");
return(AUTH_FAIL);
}
}
int main (int argc, char **argv)
{
int authResult;
if (argc < 3) {
ExitError("Usage: Provide a username and password");
}
authResult = AuthenticateUser(argv[1], argv[2]);
if (authResult != AUTH_SUCCESS) {
ExitError("Authentication failed");
}
else {
DoAuthenticatedTask(argv[1]);
}
}
CWE Version 4.14
CWE-467: Use of sizeof() on a Pointer Type
CWE-467: Use of sizeof() on a Pointer Type