简体   繁体   中英

Is it possible to free() a pointer returned by a function?

This question may well have been answered (many times) in the past, but I couldn't find any such answers by searching. It is, in any event, very much a noob question.

I created a little function that (crudely) does what the non-standard GCC function strdup() does. You pass it a string, and it checks the size, allocates enough memory to a new string, and returns it (or NULL). However, for whatever reason, I can't seem to free that pointer in the calling function. I get either a seg fault or an "invalid pointer" error at runtime.

I suspect the problem is simply caused by the fact that the pointer I'm trying to free is not the same as the one which was originally sent to malloc, and that this could easily be fixed by passing a double pointer to the function and having it assign the new string to it, and not return anything at all, but what is confusing me is the fact that I can successfully free the pointer returned by the "official" strdup() function without any problems. What gives?

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strdup2(char *buf);

int main()
{
     char *str1, *str2;

     str1 = strdup("This is the first test!");
     str2 = strdup2("This is the second test!");
     printf("%s\n%s\n", str1, str2);

     free(str1);
     puts("First pointer successfully freed.");
     free(str2);
     puts("Second pointer successfully freed.");
     return 0;
}

char *strdup2(char *buf)
{
     size_t len = strlen(buf)+1;
     char *str = malloc(len);
     if (str == NULL)
          return NULL;
     memcpy(str, buf, len);
     return buf;
}

When running it, I get:

This is the first test!
This is the second test!
First pointer successfully freed.
zsh: segmentation fault (core dumped)
return buf;

您应该返回str ,它是指向您刚刚分配的内存的指针。

You don't return the malloc() -ed pointer, you return your argument so it's a bug in your code.

More generally, you can only free() a pointer returned by a function if the function documentation specifies that it's ok to do so.

In your function strdup2 you should change :

return buf;

by :

return str;

Your Segfault comes from the fact that you are trying to free a pointer that is not the one you malloc() -ed but the argument which is a read-only string.

Yes its possible. You can free a pointer returned from a function if memory it is pointing to is allocated through malloc family function.
In your case you should return str instead of buff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM