According to this answer, constants shouldn't be deleted because they may not be allocated in the first place. However, there exists some cases where I want to protect dynamically allocated data. For example, when managing user sessions†, I want to make sure that data like the current user name won't accidentally get overwritten by other functions, but the session data are indeed allocated when they are parsed from the request.
Here is a code example to give you a better idea. Please keep in mind that things are greatly simplified, though.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *request = "www.example.com/index?first-name=SOME&last-name=DUDE";
char *get_username_from_request(const char *req) {
char *first_name = strstr(req, "first-name") + strlen("first-name") + 1;
char *last_name = strstr(req, "last-name") + strlen("last-name") + 1;
char *username = malloc(10);
memcpy(username, first_name, 4);
username[4] = ' ';
memcpy(username + 5, last_name, 4);
/* The returned string is "SOME DUDE" */
return username;
}
int main(void) {
char *username = get_username_from_request(request);
printf("Welcome, %s.\n", username);
free(username);
return 0;
}
I really want to use const char *username = get_username_from_request(request);
instead, but Clang emits a warning when I make this change:
/Applications/CLion.app/Contents/bin/cmake/bin/cmake --build /Users/nalzok/CLionProjects/zero/cmake-build-debug --target zero -- -j 2
Scanning dependencies of target zero
[ 50%] Building C object CMakeFiles/zero.dir/main.c.o
/Users/nalzok/CLionProjects/zero/main.c:24:10: warning: passing 'const char *' to parameter of type 'void *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
free(username);
^~~~~~~~
/usr/include/stdlib.h:151:18: note: passing argument to parameter here
void free(void *);
^
1 warning generated.
[100%] Linking C executable zero
[100%] Built target zero
Any idea is appreciated.
†: Well, believe it or not, I'm writing a Web application in C.