I have a function that takes a url and returns the requested file type but I cant figure out how I can free and return the malloc'd char*.
const char* lookup(const char* path){
char* rawEnding;
char* ending = malloc(strlen(path));
char* mime = malloc(strlen(path));
rawEnding = strrchr(path, '.');
if(strcasecmp(rawEnding, ".css") == 0 || strcasecmp(rawEnding, ".html") == 0 || strcasecmp(rawEnding, ".javascript") == 0 || strcasecmp(rawEnding, ".php") == 0) {
memmove(ending, rawEnding+1, strlen(rawEnding));
sprintf(mime, "text/%s", ending);
free(ending);
return mime;
} else if (strcasecmp(rawEnding, ".gif") == 0 || strcasecmp(rawEnding, ".ico") == 0 || strcasecmp(rawEnding, ".png") == 0) {
memmove(ending, ending+1, strlen(ending));
sprintf(mime, "image/%s", ending);
return mime;
} else if (strcasecmp(rawEnding, ".jpg") == 0 || strcasecmp(rawEnding, ".jpeg") == 0) {
return "text/jpeg";
} else {
return NULL;
}
}
mimeyou have to free it outisde the function.malloc'd memory orNULL.strrchrreturnsNULL. You're also not allocating enough memory for your returned string. For example, ifpathis "x.gif",mimewill point to a 5-character buffer but your code will try to put 10 characters including the terminatingNULinto those 5 characters.