前面我只是尝试执行此函数,为未知长度的字符串分配内存(即逐个字符读取,直到遇到换行符)。
现在,我的问题是关于为我的字符串(名为s)释放分配的内存。我试着使用free(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;}发布于 2017-03-08 01:16:25
考虑到性质或您的input_string_line()函数,您应该释放指针的唯一位置是main函数。任何其他地方都会产生无效的指针或导致内存泄漏.
int main()
{
char* s = input_string_line();
printf("%s",s);
free(s);
return 0;
}https://stackoverflow.com/questions/42654195
复制相似问题