0
早些時候,我只是試圖爲未知長度的字符串(即逐字符讀取,直到遇到換行符)分配內存的函數。字符串的動態內存分配函數,直到換行
現在,我的問題是關於我的字符串(命名爲s)版本的分配內存。 我試圖用免費(s)做到這一點。問題是我不知道我應該在哪裏寫它..
如果我在函數之前寫入「return s」,那麼顯然它會返回一個未分配的指針。
如果我在「return s」之後的函數中寫入它,我不認爲它會產生影響,對吧?因爲s在main()中返回,所以它永遠不會被釋放。
我該怎麼做或想到這種情況?
這是我得到:
#include <stdlib.h>
#include <stdio.h>
//Returns dynamic allocated string(read until the '\n' aka. newline character)
char* input_string_line()
{ char *s,*aux,c; //*s(string pointer),*aux(auxiliary string pointer),c(the characters that are read)
int len; //len(actual length of the string)
s=malloc(sizeof(char)); //firstly, allocation memory for 1 byte(8 bites), for the null character
if (!s) //verification if the memory can be allocated, if not possible then the program exits
{ printf("ERROR: Memory allocation failure (string).\n");
exit(EXIT_FAILURE); }
s[0] = 0; //NULL character for string ending
len = 0; //the length of the string at the beginning is 0(without considering the NULL character at the end)
while ((c = getchar()) != '\n') //reading character by character until newline
{ aux = realloc(s, len + 2); //reallocation memory for the next read character in a new auxiliary string(same as the old string, this time having memory for a new character to be added)
if (!aux) //verification if the reallocation can succed: if not possible then the program exits
{ free(s);
printf("ERROR: Memory allocation failure (auxiliary string).\n");
exit(EXIT_FAILURE); }
else s = aux; //if succeded, then the string becomes the auxiliary string
s[len] = c; //the character with the [len] index will be assigned the value of the read character
s[len+1] = 0; //NULL character for string ending
len++; } //length increments by one each time a new character is added to the string
return s;
free(s);
}
int main()
{ printf("%s",input_string_line());
return 0;}
好的,這很酷,謝謝! –
如果我只是像我一樣打印字符串呢?我還需要釋放指針嗎? case:'printf(「%s」,input_string_line());' –
是的,你必須釋放它。 C/C++沒有垃圾收集器。無論你分配什麼,你都應該釋放。否則,你會得到內存泄漏。 – Luci