I have the following function:
char * decrypt(const char *p, int key) {
char *tmp = malloc(strlen(p) + 1);
for (int i = 0; p[i] != '\0'; i++) {
if (p[i] >= 'A' && p[i] <= 'Z') {
if (key <= p[i] - 'A')
tmp[i] = p[i] - key;
else
tmp[i] = p[i] - key + 'Z' - 'A' + 1;
} else if (p[i] >= 'a' && p[i] <= 'z') {
if (key <= p[i] - 'a')
tmp[i] = p[i] - key;
else
tmp[i] = p[i] - key + 'Z' - 'A' + 1;
}
}
return tmp;
}
I'm allocating memory for the temporary pointer *temp
with:
char *tmp = malloc(strlen(p) + 1);
but I'm not freeing it anywhere.
As far as I know, there are 4 options for freeing that memory:
- Use
free()
in the same scope (which is not possible for me, because I must return the pointer) - Use
alloca()
which is not supported by every compiler (not ANSI C) malloc()
the pointer outside the function and pass that pointer to the function, thenfree()
it outside the function- assign the returned pointer to a variable and free that variable
This is the code for option #4:
char *var;
var = malloc(MAX);
var = decrypt("Hello", 1);
free(var);
Do I have to malloc()
the variable var
when I assign it a returned pointer, because that pointer is already malloc()
ed?
My questions are:
What is the best way of using malloc()
inside a function?
If I go for the 4th option, do I have to malloc()
the variable before assigning it the returned pointer?