Reputation: 41
I've written the follow function:
/*!
* @brief Checks if a string contains a certain keyword
* @param char *chkstring - String to search in
* @param char *keyword - String to search for
* @return int - 1 if found, 0 if not found
*/
int check_string(char *chkstring, char *keyword)
{
char *buffer;
char *buffer2;
buffer = malloc(256);
buffer2 = malloc(256);
strcpy(buffer2,chkstring);
if((buffer = strstr(buffer2,keyword)) != NULL) // Check for first appearance of keyword in chkstring
{
//free(buffer); // <- Problem sits here
//free(buffer2); // and/or here
return 1; // if something is found, return 1
}
else
{
free(buffer); // else return 0
free(buffer2);
return 0;
}
}
If I run it with the problematic part uncommented I get an
double free or corruption (top)
error. Why is this? Shouldn't the memory be freed in the part the function returns? Or did I messed up the if parameter and both instructions are used - which I wouldn't hope, because the code works like intended otherwise.
Thanks for your help to understand this matter!
Upvotes: 0
Views: 117
Reputation: 1493
Check strstr's return value.
Return Value
A pointer to the first occurrence in str1 of the entire sequence of characters specified in str2
, or a null
pointer if the sequence is not present in str1
This means that if str2
is found in str1
than it will return the address of the that location.
And when you free(buffer)
you are actually freeing str1
instead of the memory allocated earlier.
Also you don't need buffer = malloc(256);
EDIT: As pointed out by others, you dont need any buffers
int check_string(char *chkstring, char *keyword)
{
//No need for buffers. Simply check in original string and return accordingly
if(strstr(chkstring,keyword) != NULL) // Check for first appearance of keyword in chkstring
{
return 1; // if something is found, return 1
}
else
{
return 0;
}
}
Similar thing can be achieved by just 1 line
return (strstr(chkstring,keyword) != NULL)
//But then why do you need function if you only want if string exists or not.
Upvotes: 3