Search code examples
cfunctionpointersmallocalloca

C usage of malloc inside a function


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:

  1. Use free() in the same scope (which is not possible for me, because I must return the pointer)
  2. Use alloca() which is not supported by every compiler (not ANSI C)
  3. malloc() the pointer outside the function and pass that pointer to the function, then free() it outside the function
  4. 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?


Solution

  • It should be:

    char *var = decrypt(whatever);
    // ...use var...
    free(var);
    

    I don't know why you want to leak some memory beforehand with your code example.

    Your plan (3) of allocating memory beforehand and having the function fill it in is also viable, but it makes for more verbose code because it introduces the possibility of the function causing a buffer overflow.

    alloca wouldn't work because that space is deallocated when the function returns.