Rof*_*er4 -2 c string malloc pointers
过去这个问题很可能已被回答(很多次),但我通过搜索找不到任何这样的答案.无论如何,这是一个非常小的问题.
我创建了一个小函数(粗略地)执行非标准GCC函数strdup()的功能.你传递一个字符串,它检查大小,为新字符串分配足够的内存,并返回它(或NULL).但是,无论出于何种原因,我似乎无法在调用函数中释放该指针.我在运行时遇到seg错误或"无效指针"错误.
我怀疑这个问题只是因为我试图释放的指针与最初发送给malloc的指针不同,并且可以通过向函数传递一个双指针并且可以很容易地解决这个问题.它为它分配了新的字符串,并没有返回任何内容,但令我困惑的是,我可以成功地释放"官方"strdup()函数返回的指针而没有任何问题.是什么赋予了?
这是代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
运行时,我得到:
This is the first test!
This is the second test!
First pointer successfully freed.
zsh: segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)