1594
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 2:
This code attempts to tokenize a string and place it into an array using the strsep function, which
inserts a \0 byte in place of whitespace or a tab character. After finishing the loop, each string in the
AP array points to a location within the input string.
Example Language: C (Bad)
char **ap, *argv[10], *inputstring;
for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;)
if (**ap != '\0')
if (++ap >= &argv[10])
break;
/.../
free(ap[4]);
CWE Version 4.14
CWE-761: Free of Pointer not at Start of Buffer
CWE-761: Free of Pointer not at Start of Buffer