1602
Example Language: C (Bad)
#define SUCCESS (1)
#define FAILURE (0)
int contains_char(char c){
char *str;
str = (char*)malloc(20*sizeof(char));
strcpy(str, "Search Me!");
while( *str != NULL){
if( *str == c ){
/* matched char, free string and return success */
free(str);
return SUCCESS;
}
/* didn't match yet, increment pointer and try next char */
str = str + 1;
}
/* we did not match the char in the string, free mem and return failure */
free(str);
return FAILURE;
}
However, if the character is not at the beginning of the string, or if it is not in the string at all, then
the pointer will not be at the start of the buffer when the programmer frees it.
Instead of freeing the pointer in the middle of the buffer, the programmer can use an indexing
pointer to step through the memory or abstract the memory calculations by using array indexing.
Example Language: C (Good)
#define SUCCESS (1)
#define FAILURE (0)
int cointains_char(char c){
char *str;
int i = 0;
str = (char*)malloc(20*sizeof(char));
strcpy(str, "Search Me!");
while( i < strlen(str) ){
if( str[i] == c ){
/* matched char, free string and return success */
free(str);
return SUCCESS;
}
/* didn't match yet, increment pointer and try next char */
i = i + 1;
}
/* we did not match the char in the string, free mem and return failure */
free(str);
return FAILURE;
}
Example 4:
Consider the following code in the context of a parsing application to extract commands out of user
data. The intent is to parse each command and add it to a queue of commands to be executed,
discarding each malformed entry.
Example Language: C (Bad)
//hardcode input length for simplicity
char* input = (char*) malloc(40*sizeof(char));
char *tok;
char* sep = " \t";
get_user_input( input );
/* The following loop will parse and process each token in the input string */
tok = strtok( input, sep);
while( NULL != tok ){
CWE Version 4.14
CWE-763: Release of Invalid Pointer or Reference
CWE-763: Release of Invalid Pointer or Reference