我正在尝试使用valgrind验证以下代码文件test.c,当我进行gcc test.c -o test时出现以下错误
Syscall param write(buf) points to uninitialised byte(s)
==22765== at 0x4F22870: __write_nocancel (syscall-template.S:81)
==22765== by 0x4EB0002: _IO_file_write@@GLIBC_2.2.5 (fileops.c:1261)
==22765== by 0x4EB14DB: _IO_do_write@@GLIBC_2.2.5 (fileops.c:538)
==22765== by 0x4EB0D5F: _IO_file_close_it@@GLIBC_2.2.5 (fileops.c:165)
==22765== by 0x4EA4B0F: fclose@@GLIBC_2.2.5 (iofclose.c:59)
==22765== by 0x400986: main (in /home/grados-sanchez/git/merkle-codigos-C/test)
==22765== Address 0x4025770 is not stack'd, malloc'd or (recently) free'd
==22765== Uninitialised value was created by a stack allocation
==22765== at 0x4007E2: node_write (in /home/grados-sanchez/git/merkle-codigos-C/test)
但是当我运行gcc test.c -o test然后使用valgrind时,我没有得到任何错误。我的问题是在这种情况下valgrind会发生什么?有什么办法可以让valgrind运行32或64位?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define id_lenght 6000
typedef unsigned char * ustring;
typedef struct {
ustring ustr;
int height;
char id[id_lenght];
} node;
int validation_read(void * ptr_var, size_t sizeof_datatype, int num,
FILE * ptr_file) {
if (fread(ptr_var, sizeof_datatype, num, ptr_file) <= 0) {
printf("Error reading file");
return 1;
}
return 0;
}
void node_read(FILE * node_ptr, node * n, int r) {
int i;
validation_read(n->id, sizeof(unsigned char), id_lenght, node_ptr);
validation_read(&(n->height), sizeof(int), 1, node_ptr);
validation_read(n->ustr, sizeof(unsigned char) * (r + 1), 1,node_ptr);
}
void node_init(node * n, int r) {
memset(n, 0, sizeof(node));
n->ustr = malloc((r + 1) * sizeof(unsigned char));
memset(n->ustr, 0, (r + 1));
n->ustr[r] = 0;
n->height = -1;
memset(n->id,0,id_lenght+1);
}
void node_write(FILE * node_ptr, node * n, int r) {
int i;
char newid[id_lenght];
memset(newid,0,id_lenght);
sprintf(newid,"%s",n->id);
fwrite(newid, sizeof(char), id_lenght+1, node_ptr);
fwrite(&(n->height), sizeof(int), 1, node_ptr);
fwrite(n->ustr, sizeof(unsigned char) * (r + 1), 1,node_ptr);
}
void node_destroy(node * n) {
free(n->ustr);
n->height = -1;
}
int main(){
FILE * ptr = fopen("juantest","w+");
int r = 64/8;
node in;
node_init(&in, r);
node_write(ptr, &in, r);
node_destroy(&in);
fclose(ptr);
}
编辑但是当我尝试读取文件时会发生问题。我编辑了上面的代码。我收到读取文件错误读取文件错误读取文件错误
Valgrind的担心是对的。在这条线
fwrite(newid, sizeof(char), id_lenght+1, node_ptr);
您正在写入比允许的多1个字节的数据;一个超出您的新临时堆栈字符串的字符串。您可能将写一个字符串(以a+1
表示结尾的零)与精确地写出所使用的(最大)缓冲区大小混淆了:
fwrite(newid, sizeof(char), id_length, node_ptr);
由于要将内存内容转储到文件中,因此在使用之前先清除字符串内存是正确的sprintf
。您永远不知道新分配的内存中有什么!
请注意,如果您担心数据的完整性,最好改用safe变量sprintf_s
,因为它可以防止您过度使用此缓冲区。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句