【问题标题】:realloc() invalid pointer error when increasing size of string in a function增加函数中字符串的大小时,realloc()无效指针错误
【发布时间】:2018-11-03 10:07:07
【问题描述】:

当我运行代码时,它显示realloc() 无效指针错误。

input() 函数有什么问题吗?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
char *input(void)
{
    int n = 1;
    char *str = malloc(sizeof(char));
    *str = '\0';
    while((*str=getchar())!='\n')
    {
        n++;
        str = realloc(str,sizeof(char)*n);
        str++;
    }
    return str;
}

int main(int argc, char const *argv[])
{
    char *str = input();
    printf("%s",str);
    free(str);
    return 0;
}

【问题讨论】:

    标签: c dynamic-memory-allocation c89


    【解决方案1】:

    你犯了一些错误:

    • 返回字符串的结尾,而不是开头。

    • realloc 需要原始地址(见 Thomas 的回答)

    • realloc 可能会返回一个新地址

    • 你没有终止字符串。

    以下内容修复了这些错误并提供了一些建议:

    char *input(void)
    {
        size_t i=0;
        int c;
        char *str = malloc(1);
        if (!str) return 0;
        while((c=getchar())!=EOF && c!='\n')
        {
            str[i]= c;
            if ((newstr = realloc(str,i+1))==0)
                break;          // out of memory: return what we have
            str= newstr;
            i++;
        }
        str[i]= '\0';
        return str;
    }
    

    【讨论】:

    • 我建议进行两项更改:(1) 跳过始终为 1 的 sizeof(char),至少对我来说这是一种代码味道。 (2) 使用整数作为分配字符串的索引,而不是额外的指针,以避免指针运算。
    • 如果在读取换行符之前检测到EOF,显示的代码将会失败。
    • 这个if (newstr != str) 可能会调用未定义的行为,因为str 可能指向realloc() 之后的无效内存。
    • @alk,固定EOF。我不确定未定义的行为评论。 str 指针(变量)与另一个指针(变量)进行比较,无论指向的内存是否仍然有效。如果是未定义行为,则无法检查新指针是否与旧指针不同,并且必须始终进行赋值。
    • “无法检查新指针是否与旧指针不同”这是真的。但从来不需要这样做。
    【解决方案2】:

    执行str++ 后,指针不再指向分配字符串的开头。 realloc 需要原始指针,而不是指向分配数据内部某处的指针。

    【讨论】:

      【解决方案3】:

      一种没有冗余调用和完整错误检查的方法:

      #include <stdio.h>
      #include <stdlib.h>
      
      char *input(void)
      {
        size_t n = 0;
        char * str = NULL;
      
        do
        {
          ++n;
      
          {
            void * pv = realloc(str, (n + 1) * sizeof *str);
            if (NULL == pv)
            {
              perror("realloc() failed");
      
              break;
            }
      
            str = pv;
          }
      
          {
            int result = getchar();
      
            if (EOF == result)
            {
              if (ferror(stdin))
              {
                fprintf(stderr, "getchar() failed\n");
              }
      
              --n;
      
              break;
            }
      
            str[n - 1] = result;
          }
        } while ('\n' != str[n - 1]);
      
        if (NULL != str)
        {
          str[n] = '\0';
        }
      
        return str;
      }
      
      int main(int argc, char const *argv[])
      {
        int result = EXIT_SUCCESS; /* Be optimistic. */
      
        char * str = input();
        if (NULL == str)
        {
          result = EXIT_FAILURE;
      
          fprintf(stderr, "input() failed\n");
        }
        else
        {
          printf("input is: '%s'\n", str);
        }
      
        free(str);
      
        return result;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-13
        • 2017-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多