首页 > 解决方案 > 为什么不重新分配额外内存就不会触发错误,C语言

问题描述

我是 C 语言新手,教程在这里

我按照教程进行操作,但是当我尝试不重新分配内存时它不会出错,

无论是否注释 realloc 代码,结果都是相同的。

我想知道为什么?有人可以解释一下吗?谢谢

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

int main()
{
    char name[100];
    char *description;

    strcpy(name, "Zara Ali");

    description = (char *) malloc(30 * sizeof(char));
    if (description == NULL)
    {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    }
    else
    {
        strcpy(description, "Zara li a DPS student.");
    }
//    description = (char *) realloc(description, 100 * sizeof(char));
    if (description == NULL)
    {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    }
    else
    {
        strcat(description, "She is in class 10th.");
    }
    printf("Name = %s\n", name);
    printf("Description: %s\n", description);

    free(description);
}

结果:图片

标签: c

解决方案


description在您的代码中,您初始化

description = (char *) malloc(30 * sizeof(char)); 这意味着 的值description不为NULL

您的printf陈述依赖于if (description == NULL)返回 true 的检查,但它description仍然不是NULL

realloc将返回 NULL,因此设置descriptionNULL如果分配内存失败。


推荐阅读