我有点困惑与字符指针的概念,所以我做了一个简单的代码只是打印由用户(我)提供了我的名字。我也想练习malloc,所以我引用了指向RAM中某个内存的指针,但是我真的不知道在“sizeof(char)*”之后应该放什么,因为这是用户输入,尚未确定。 此外,这样做后,我释放的内存,但我得到了命令行上一个错误消息说:char指针和malloc的
*** Error in `./char': double free or corruption (fasttop): 0x00000000017fe030 ***
Aborted
好像我释放了相同内存的两倍或东西,但我不知道该怎么删除或添加。请帮忙!
#include <stdio.h>
#include <cs50.h>
int main (void)
{
char *strings = malloc(sizeof(char) * 10);
printf("What is your name?\n");
//wait for use to type his/her name
strings = get_string();
printf("Hello %s\n", strings);
free (strings);
return 0;
}
什么是get_string?它是否定义了C语言?你应该通过分配的内存来获取字符串,并在那里填充数组。不覆盖。请添加代码'get_string' –
根据https://cs50.stackexchange.com/questions/21617/whats-the-c-equivalent-for-string-input-getstring的答案,'cs50.h'具有函数名称是'GetString()'而不是'get_string()'。 – rsp
运行时应该没有问题,只是内存泄漏。你是否复制并粘贴或重新输入? – molbdnilo