To set the final character to null, I'd just do: tmp[strlen(s)] = '\0';
That's a good habit, quzah, but strcpy automatically appends a null to the end of the target, so no need there...
All in all, I think the coding is good style and better than average. Good work, Tracker.
Still, not freeing memory is not very good, if not just because it is needlessly wasteful. So my suggestion would be to free it just before returning from the function.
There are a few discrepancies too. You loop through "temp", but why? Look ->
Code:
char *get_field(const char *s, char *name)
{
char *tmp, *field;
int i;
tmp = (char *) malloc(strlen(s)+1);
if (!tmp)
return NULL;
strcpy(tmp, s);
if ((field = strstr(tmp, name)) != NULL)
field += strlen(name);
//..........all done!........//
free(temp);
return field; /* NULL if not found */
}
Anyway, it is a cool function.
Here's another way, too:
Code:
char *get_field(const char *s, char *name)
{
char *field;
field = strstr( s, name );
if( field != NULL)
field += strlen(name);
return field; /* NULL if not found */
}