我有點困惑與字符指針的概念,所以我做了一個簡單的代碼只是打印由用戶(我)提供了我的名字。我也想練習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