4

我有一个包含交易数组的 BankAccount 结构。存款和取款在此数组中存储为 +/- 整数。

struct BankAccount {
    char name[NAME_LENGTH];
    int num_of_transactions;
    int transactions[MAX_TRANSACTIONS];
};

我正在为堆上的结构分配空间并在完成后处理它。我使用 fwrite 将此结构保存到文件中。

struct BankAccount *new_bank_account(char name[], int initial_deposit) {
    struct BankAccount *acc = malloc(sizeof(struct BankAccount));

    strncpy(acc->name, name, NAME_LENGTH);
    acc->num_of_transactions = 0;

    int i;
    for (i = 0; i < MAX_TRANSACTIONS; i++) {
        acc->transactions[i] = 0;
    }

    if (initial_deposit != 0) {
        make_deposit(acc, initial_deposit);
    }

    return acc;
}

void delete_bank_account(struct BankAccount *acc) {
    free(acc);
}

int save_bank_account(struct BankAccount *acc, char filepath[]) {
    FILE *fp = fopen(filepath, "w");
    int res = 0;

    res = fwrite(acc, sizeof(struct BankAccount), 1, fp);

    fclose(fp);
    return res;
}

代码按预期工作,我能够在帐户上进行交易并将其保存到磁盘并重新加载它。我的测试代码如下。

void test_bank_account_balance() {
    struct BankAccount *acc = new_bank_account("John Doe", 0);
    make_deposit(acc, 50);
    make_deposit(acc, 100);
    make_withdrawal(acc, 50);

    printf("%s has balance = $ %d\n", acc->name, get_balance(acc));

    delete_bank_account(acc);
}

int main(int argc, char *argv[]) {
    test_save_bank_account();
    return 0;
}

但是,当我通过 valgrind 运行它时,它会给我关于未初始化字节的错误。我怀疑 new_bank_account 中缺少一些初始化。但我看不出那是什么。

==4311== Syscall param write(buf) points to uninitialised byte(s)
==4311==    at 0x411E1D3: __write_nocancel (syscall-template.S:82)
==4311==    by 0x40B2B04: _IO_file_write@@GLIBC_2.1 (fileops.c:1289)
==4311==    by 0x40B29E3: new_do_write (fileops.c:543)
==4311==    by 0x80489B0: test_save_bank_account (p14.c:124)
==4311==    by 0x8048A1D: main (p14.c:140)
==4311==  Address 0x4035032 is not stack'd, malloc'd or (recently) free'd
==4311==  Uninitialised value was created by a heap allocation
==4311==    at 0x402BD14: malloc (vg_replace_malloc.c:270)
==4311==    by 0x80486B5: new_bank_account (p14.c:41)
==4311==    by 0x8048956: test_save_bank_account (p14.c:118)
==4311==    by 0x8048A1D: main (p14.c:140)

请帮忙!谢谢。

4

1 回答 1

5

我猜在namenum_of_transactions的成员之间有一些填充struct BankAccount

这可能没什么好担心的,但是如果你想使 valgrind 静音,使用calloc()分配内存应该可以工作。或memset(acc, 0, sizeof(*acc))

于 2012-09-14T06:55:44.113 回答