【问题标题】:C dynamic memory allocationC 动态内存分配
【发布时间】:2015-12-07 15:54:23
【问题描述】:

我正在学习 C,但我仍然是菜鸟。 我正在编写一个程序作为动态内存分配的练习,它从用户那里获取长度未知的文本,并返回没有空格、制表符、特殊字符或数字的文本。 该程序似乎工作正常,只是某些文本似乎因未知原因更改为未知字符。 代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *pstring;
    pstring = (char *)malloc( sizeof(char));

    char c = '$';

    int i = 0;
    while(c != '\n')
    {
        c = getchar();
        if(isalpha(c))
        {
            pstring[i] = c;
            realloc(pstring, (i+2)*sizeof(char));
            i++;
        }
    }

    int j;
    for(j = 0; j < i; j++)
    {
        printf("%c", pstring[j]);
    }

    return 0;
}

工作正常:

问题是:

【问题讨论】:

标签: c malloc dynamic-memory-allocation realloc calloc


【解决方案1】:

realloc 函数可以扩展现有内存,但是它也可能(并且可能大部分时间都这样做)完全分配 内存。它返回它重新分配的内存,并且你不使用返回的指针。

另外,如果realloc 失败,那么它将返回NULL,因此不要将返回的指针分配给您在realloc 调用中使用的变量,否则您将丢失原始指针。使用临时变量,检查NULL,然后重新分配给实际的指针变量。

在不相关的注释中,sizeof(char) 被指定为始终为 1


最后一句警告。您现在处理“字符串”的方式可以正常工作(在解决了您现在或当然遇到的问题之后),但是如果您想将数据视为“正确”的 C 字符串,您需要分配一个额外的字符,因为 C字符串以空字符 '\0' 终止(不要与空指针 NULL 混淆)。

如果您的字符串没有此终止符,则使用任何标准字符串函数都会导致未定义的行为,因为它很可能会超出分配的内存范围。

【讨论】:

    【解决方案2】:

    正如 Joachim Pileborg 所说,realloc 可能会将内存块移动到新位置,我们应该将指针更改为新位置

    Here is useful link about realloc function 我现在的工作代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char *pstring, *ptemp;
        pstring = (char *)malloc( sizeof(char));
    
        char c = '$';
    
        int i = 0;
        while(c != '\n')
        {
            c = getchar();
            if(isalpha(c))
            {
                pstring[i] = c;
                ptemp = realloc(pstring, (i+2)*sizeof(char));
                if(ptemp != NULL)
                {
                    pstring = ptemp;
                    i++;
                }
            }
        }
    
        int j;
        for(j = 0; j < i; j++)
        {
            printf("%c", pstring[j]);
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2021-02-28
      • 2012-01-20
      • 1970-01-01
      • 2015-09-25
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多