Free():尝试使用功能复制字符串后的编译指针错误
我正在尝试使用一个函数复制字符串:
#include <stdlib.h>
#include <stdio.h>
char *_strdup(char *str);
/**
* main - Entry point of my program
*
* Return: Always 0.
*/
int main(void)
{
char *s;
s = _strdup("Copied String");
if (s == NULL)
{
printf("failed to allocate memory\n");
return (1);
}
printf("%s\n", s);
free(s);
return (0);
}
/**
* _strdup - This function returns a pointer to a new string
* which is a duplicate of the string str
*
* @str: The string to be copied
*
* Return: On Success, this function returns a pointer to
* the duplicated string. It returns NULL, if insufficent
* memory was avaliable, and if str == NULL.
*/
char *_strdup(char *str)
{
char *ch;
if (str == NULL)
{
return (NULL);
}
ch = malloc(sizeof(*ch) * sizeof(*str));
ch = str;
return (ch);
}
在运行它时,我会收到以下错误:
Copied String
free(): invalid pointer
Aborted (core dumped)
它已复制了字符串,但是当我尝试释放分配的内存空间时,它给了我一个错误。为什么我会发生?我该如何解决?
I am trying to copy a string using a function:
#include <stdlib.h>
#include <stdio.h>
char *_strdup(char *str);
/**
* main - Entry point of my program
*
* Return: Always 0.
*/
int main(void)
{
char *s;
s = _strdup("Copied String");
if (s == NULL)
{
printf("failed to allocate memory\n");
return (1);
}
printf("%s\n", s);
free(s);
return (0);
}
/**
* _strdup - This function returns a pointer to a new string
* which is a duplicate of the string str
*
* @str: The string to be copied
*
* Return: On Success, this function returns a pointer to
* the duplicated string. It returns NULL, if insufficent
* memory was avaliable, and if str == NULL.
*/
char *_strdup(char *str)
{
char *ch;
if (str == NULL)
{
return (NULL);
}
ch = malloc(sizeof(*ch) * sizeof(*str));
ch = str;
return (ch);
}
As I run it, I get the following error:
Copied String
free(): invalid pointer
Aborted (core dumped)
It has copied the string, but as I try to free the memory space allocated it gives me an error. Why i it happening? How can I get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里,您可以合法地使用
free()
on。ch = malloc(sizeof(*ch)*sizeof(*str));
。尽管我怀疑那里的大小的计算。...
在这里,在下一行中,您将其扔掉,然后用无法合法使用
free()
上的东西代替它。ch = str;
,然后您将其返回到尝试使用
free()
的位置。return(ch);
总共尝试
free(“复制字符串”);
Here you malloc something which you could legally use
free()
on.ch = malloc(sizeof(*ch) * sizeof(*str));
.Though I doubt the calculation of the size there....
Here, right in the next line, you throw that away and replace it by something which you can not legally use
free()
on.ch = str;
And then you return it towards where it you attempt to use
free()
on it.return (ch);
In total you basically attempt
free("Copied String");