我正在爲變量n0中的struct節點分配空間。我使用fwrite將此結構保存到文件中,但是當我運行valgrind時,出現此錯誤。我的代碼在下面,你能幫我嗎?將struct + write(buf)指向未初始化的字節
==1412== Syscall param write(buf) points to uninitialised byte(s)
==1412== at 0x4F22870: __write_nocancel (syscall-template.S:81)
==1412== by 0x4EB0002: [email protected]@GLIBC_2.2.5 (fileops.c:1261)
==1412== by 0x4EB14DB: [email protected]@GLIBC_2.2.5 (fileops.c:538)
==1412== by 0x4EB0D5F: [email protected]@GLIBC_2.2.5 (fileops.c:165)
==1412== by 0x4EA4B0F: [email protected]@GLIBC_2.2.5 (iofclose.c:59)
==1412== by 0x400793: main (in /home/grados-sanchez/git/merkle-codigos-C/test_file)
==1412== Address 0x402500c is not stack'd, malloc'd or (recently) free'd
==1412== Uninitialised value was created by a stack allocation
==1412== at 0x40073F: main (in /home/grados-sanchez/git/merkle-codigos-C/test_file)
typedef struct {
unsigned char * ustr;
int height;
}node;
void node_init(node * n, int r) {
int i;
n->ustr = malloc((r + 1) * sizeof(unsigned char));
for (i = 0; i < r; i++) {
(n->ustr)[i] = random() & 0xff;
}
(n->ustr)[r] = 0;
n->height = -1;
}
void node_destroy(node * n) {
free(n->ustr);
n->height = -1;
}
int main() {
FILE* file_ptr = fopen("file1", "w+");
node n0;
node_init(&n0,2);
fwrite(&n0, sizeof(node), 1, file_ptr);
fclose(file_ptr);
node_destroy(&n0);
return 0;
}
這段代碼只會寫一個'unsigned char *'和一個int文件。不是節點字符串的內容。如果這就是你想要的,代碼應該沒問題。 –
@BrianMcFarland通過您的評論,感謝我如何修復錯誤「(請注意,它正在寫入指針本身的值,而不是它指向的值,這可能不是您想要的,但這是一個單獨的問題)」 ? – Juan