释放内存时为什么会出现运行时错误?

时间:2018-01-26 16:02:46

标签: c

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

typedef struct a {
    int n;
    char *p;
} a;

int main()
{
    a A;
    A.p = (char *)malloc(20 * sizeof(char));

    A.n = 100;
    strcpy(A.p, "just testing");
    //A.p = "just testing" <-- runtime error

    printf("%d\n%s\n", A.n, A.p);

    free(A.p);

    return 0;
}

如果您使用strcpy,它将毫无问题地运行。

但是,给出类似A.p = "just testing的字符串会导致运行时错误。

如果直接输入字符串,为什么会出错?

使用strcpy和直接放置它有什么区别?

3 个答案:

答案 0 :(得分:6)

A.p = "just testing"使指针p指向字符串文字"just testing"。您分配的内存现已丢失,程序内存泄漏。现在您正在尝试释放未由mallocrealloccalloc分配的内存。
如果未分配内存,则free的行为未定义,指针pmallocrealloccalloc

答案 1 :(得分:2)

strcpy 副本字符串文字"just testing"的内容放入A.p指向的内存位置(由malloc返回)。

相反,赋值将字符串文字"just testing"的地址分配给A.p,其中覆盖malloc返回的内存地址。当您稍后调用free时,您将传递字符串文字的地址而不是malloc的内存。将地址传递给未从free返回的malloc会调用undefined behavior,在这种情况下会显示崩溃。

答案 2 :(得分:0)

结构“a”中的变量“p”是指针,因此“p”只能被赋予对变量所在的内存空间的引用。这里enter image description here是一个可以获取指针信息的地方。但是与您的问题相关,您必须分配引用而不是字符串值。例如,声明char r =“hi”并且赋值语句可以是A.p =&amp; r;此致!

相关问题