首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字符串到换行符的动态内存分配函数

字符串到换行符的动态内存分配函数
EN

Stack Overflow用户
提问于 2017-03-08 01:10:02
回答 1查看 135关注 0票数 0

前面我只是尝试执行此函数,为未知长度的字符串分配内存(即逐个字符读取,直到遇到换行符)。

现在,我的问题是关于为我的字符串(名为s)释放分配的内存。我试着使用free(s)来做这件事。问题是我不知道该把它写在哪里。

如果我把它写在函数中的"return s“之前,那么很明显,它会返回一个未分配的指针。

如果我把它写在"return s“后面的函数中,我认为它不会有什么效果,对吧?因为它永远不会被释放,因为s在main()中返回。

对于这种情况,我应该怎么做或怎么考虑?

这是我得到的:

代码语言:javascript
运行
复制
#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;}
EN

Stack Overflow用户

发布于 2017-03-08 01:16:25

考虑到性质或您的input_string_line()函数,您应该释放指针的唯一位置是main函数。任何其他地方都会产生无效的指针或导致内存泄漏.

代码语言:javascript
运行
复制
int main()
{ 
  char* s = input_string_line();
  printf("%s",s);
  free(s);
  return 0;
}
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42654195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档