【问题标题】:Data becomes modified during printf数据在 printf 期间被修改
【发布时间】:2015-02-08 01:11:03
【问题描述】:

在我从文件中读取一些数据后,将其分配给节点内的结构类型记录,数据与文件的数据匹配。在我离开读取功能并返回主数据后,数据仍然保持不变。但是当我尝试打印它时,它变得一团糟。

加载函数

void load(FILE *file, Node *head)
{
    char tempArtist[30]={'\0'}, tempAlbum[30]={'\0'}, tempTitle[30]={'\0'}, tempGenre[30]={'\0'},tempSpace='\0';
    SongLength *tempLength=NULL;
    int tempPlay=0, tempRating=0, tempMins=0, tempSecs=0;

    tempLength = (SongLength*)malloc(sizeof(SongLength));

    fscanf(file,"%s",&tempArtist);
    fscanf(file,"%s",&tempAlbum);
    fscanf(file,"%s",&tempTitle);
    fscanf(file,"%s",&tempGenre);
    fscanf(file,"%s",&tempMins);
    fscanf(file,"%s",&tempSecs);
    fscanf(file,"%s",&tempPlay);
    fscanf(file,"%s",&tempRating);
    fscanf(file,"%c",&tempSpace);

    tempLength->mins=&tempMins;
    tempLength->secs=&tempSecs;

    head->data->album=tempAlbum;
    head->data->artist=tempArtist;
    head->data->genre=tempGenre;
    head->data->song=tempTitle;
    head->data->length=tempLength;
    head->data->played=tempPlay;
    head->data->rating=tempRating;
}

打印测试功能

int main(void)
{
    FILE *loadFile = NULL;
    Node *head=NULL;

    head=(Node*)malloc(sizeof(Node));
    head->data=(Record*)malloc(sizeof(Record));
    head->data->length=(SongLength*)malloc(sizeof(SongLength));

    loadFile=fopen("records.txt","r");

    load(loadFile,head);
    head->data->artist; // artist matches the name in load file (aka snoop)
    printf("%s", head->data->artist); // When trying to print here it prints a smiley face
}

便于复制的额外信息

typedef struct songlength
{
    int *mins;
    int *secs;
}SongLength;


typedef struct record
{
    char *artist;
    char *album;
    char *song;
    char *genre;
    struct songlength *length;
    int played;
    int rating;

}Record;

typedef struct node
{
    struct node *pPrev;
    struct record *data;
    struct node *pNext;

}Node;

文件数据格式

snoop
heartbeat
swiggity
rap
03
10
25
4

【问题讨论】:

    标签: c linked-list malloc


    【解决方案1】:

    您拥有undefined behavior,因为您将指向本地数组的指针分配给head 结构。

    例如,一旦函数load 返回,数组tempArtist超出范围,因此任何指向该数组的指针(如head->artist)都将是杂散指针,并且取消引用这些指针将导致上述未定义的行为。

    【讨论】:

    • 那么,解决此类问题的最佳方法是什么?
    • @user3482104 真的有两种解决方案:要么动态分配结构中的指针并复制字符串,要么在结构数组中创建字符串并复制字符串。
    猜你喜欢
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    相关资源
    最近更新 更多