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