1595
Since strsep is not allocating any new memory, freeing an element in the middle of the array is
equivalent to free a pointer in the middle of inputstring.
Example 3:
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 ){
if( isMalformed( tok ) ){
/* ignore and discard bad data */
free( tok );
}
else{
add_to_command_queue( tok );
}
tok = strtok( NULL, sep));
}
While the above code attempts to free memory associated with bad commands, since the memory
was all allocated in one chunk, it must all be freed together.
One way to fix this problem would be to copy the commands into a new memory location before
placing them in the queue. Then, after all commands have been processed, the memory can safely
be freed.
Example Language: C (Good)
//hardcode input length for simplicity
char* input = (char*) malloc(40*sizeof(char));
char *tok, *command;
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 ){
if( !isMalformed( command ) ){
/* copy and enqueue good data */
command = (char*) malloc( (strlen(tok) + 1) * sizeof(char) );
strcpy( command, tok );
add_to_command_queue( command );
}
tok = strtok( NULL, sep));
}
free( input )
Observed Examples
Reference Description
CVE-2019-11930 function "internally calls 'calloc' and returns a pointer at an index... inside the
allocated buffer. This led to freeing invalid memory."
https://www.cve.org/CVERecord?id=CVE-2019-11930
Affected Resources
• Memory
CWE Version 4.14
CWE-762: Mismatched Memory Management Routines
CWE-762: Mismatched Memory Management Routines