简体   繁体   English

从C中的结构成员char数组打印char数组时fopen数据损坏

[英]fopen data corruption when printing char arrays from structure member char arrays in C

I'm having some kind of weird error where the lastName and phoneNumber char array members of the struct phoneEntry are overwritten when I'm trying to print. 我有一些奇怪的错误,当我尝试打印时,struct phoneEntry的lastName和phoneNumber char数组成员被覆盖。 The following code is bits and pieces of code that relate to the main part that strikes out. 以下代码是与突出显示的主要部分相关的位和代码段。

typedef struct
{
    char firstName[30];
    char lastName[30];
    char phoneNumber[30];
} phoneEntry;

size_t phoneBookSize = 1;
phoneEntry* ptrPhoneBook = malloc(phoneBookSize * sizeof(phoneEntry));


FILE *loadedFile;
char fileName[30];
scanf("%s", fileName);
loadedFile = fopen(fileName, "w"); // ERROR OCCURS

fprintf(loadedFile, "First name\tLast name\tPhone Number\n");
int count = 0;
for (count = 0; count < phoneBookSize - 1; count++)
{
    printf("saving %s %s %s\n", ptrPhoneBook[count].firstName, ptrPhoneBook[count].lastName, ptrPhoneBook[count].phoneNumber);
    fprintf(loadedFile, "%s\t%s\t%s\t\n", ptrPhoneBook[count].firstName, ptrPhoneBook[count].lastName, ptrPhoneBook[count].phoneNumber);
}
fclose(loadedFile);

Basically, the data stored in each character array within the struct member is defined and exists until the "loadedFile" initialization. 基本上,存储在struct成员中的每个字符数组中的数据被定义并存在,直到“loadedFile”初始化。 At that point, the data stored in the lastname and phoneNumber char array members within the ptrPhoneBook at index 0 is overwritten with nothing or simply erased. 此时,存储在索引0处的ptrPhoneBook中的lastname和phoneNumber char数组成员中的数据将被覆盖,或者只是被擦除。

This is the output: 这是输出:

First name  Last name   Phone Number
James   

As opposed to the expected output: 与预期的产出相反:

First name  Last name       Phone Number
James       Bond            007

I can avoid the entire problem by simply starting the count of the ptrPhoneBook at 1 as opposed to 0, but I want to know why fopen corrupts these data members at index 0. 我可以通过简单地将ptrPhoneBook的计数设置为1而不是0来避免整个问题,但我想知道为什么fopen会破坏索引0处的这些数据成员。

The code I gave probably won't give you an exact output, but the error still exists. 我给出的代码可能不会给你一个确切的输出,但错误仍然存​​在。

If you would like to try and run the code yourself, here's code that you can run right of the bat. 如果您想尝试自己运行代码,这里的代码可以直接运行。

// Including libraries into the source code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char firstName[30];
    char lastName[30];
    char phoneNumber[30];
} phoneEntry;

main()
{

    size_t phoneBookSize = 1;
    phoneEntry* ptrPhoneBook = malloc(phoneBookSize * sizeof(phoneEntry));

    phoneBookSize++;
    phoneEntry* reallocPhoneBook = realloc(ptrPhoneBook, phoneBookSize);

    if (reallocPhoneBook) {
        ptrPhoneBook = reallocPhoneBook;
    } else {
        printf("Failure. Memory error.\n\n");
    }

    strcpy(ptrPhoneBook[0].firstName, "James");
    strcpy(ptrPhoneBook[0].lastName, "Kim");
    strcpy(ptrPhoneBook[0].phoneNumber, "2343");


    FILE *loadedFile;
    char fileName[30];
    scanf("%s", fileName);
    loadedFile = fopen(fileName, "w");

    fprintf(loadedFile, "First name\tLast name\tPhone Number\n");
    int count = 0;
    for (count = 0; count < phoneBookSize - 1; count++)
    {
        printf("saving %s %s %s\n", ptrPhoneBook[count].firstName, ptrPhoneBook[count].lastName, ptrPhoneBook[count].phoneNumber);
        fprintf(loadedFile, "%s\t%s\t%s\t\n", ptrPhoneBook[count].firstName, ptrPhoneBook[count].lastName, ptrPhoneBook[count].phoneNumber);
    }
    fclose(loadedFile);
}

The output for the code above is: 上面代码的输出是:

First name  Last name   Phone Number
James   2343    

The realloc is totally bogus, as it allocates 2 bytes instead of 2 phone entries : realloc完全是假的,因为它分配2个字节而不是2个电话条目

size_t phoneBookSize = 1;
/* ... */
phoneBookSize++;
phoneEntry* reallocPhoneBook = realloc(ptrPhoneBook, phoneBookSize);

/* ... */
ptrPhoneBook = reallocPhoneBook;

You probably meant: 你可能意味着:

realloc(ptrPhoneBook, phoneBookSize * sizeof(phoneEntry))

+1 for cnicutar's answer - the realloc looks like problem 1. 对于cnicutar的回答+1 - realloc看起来像问题1。

However, your for loop is also wrong: you're looping while count < phoneBookSize - 1 which skips the last entry - change it to count < phoneBookSize eg if phoneBookSize is 3, you should go upto array index [2] 但是,你的for循环也是错误的:你循环count < phoneBookSize - 1跳过最后一个条目 - 把它改成count < phoneBookSize例如,如果phoneBookSize是3,你应该达到数组索引[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM