我正在测试malloc以查看如果程序在没有free()的情况下退出,则分配的内存是否保留其数据。我将地址保存到文件中,并在另一个程序中使用这些地址进行测试,但是它崩溃了,为什么会发生?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
int main(void)
{
    FILE *file;
    if(fopen_s(&file,"file.txt","w"))
        exit(-1);
    char *p1 = (char*)malloc(10*sizeof(char));
    char *p2 = (char*)malloc(10*sizeof(char));

    strcpy(p1,"A");
    strcpy(p2,"B");

    fprintf(file,"%x\n",p1);
    fprintf(file,"%x\n",p2);

    fclose(file);
    return 0;
}
*/
int main(void)
{
    //these two addresses are from the saved file
    char *p1 = (char*)0x341440;
    char *p2 = (char*)0x341468;

    printf("%s\n",p1);
    printf("%s\n",p2);

    return 0;
}

最佳答案

它崩溃是因为malloc在两次运行之间不保存其内容,因此在第二次运行中,您将从未初始化的指针进行打印。

您期望“前提失败”是什么样子?有效的打印件,但是具有不同的值?

关于c - 尝试从分配的内存中打印字符串时程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34123826/

10-11 22:58
查看更多