我在C语言中读取文件并复制字符数组时遇到缓冲区溢出。有三段可能令人反感的代码,我无法弄清楚哪里出了问题。
第一个读取文件并将其填充到哈希图中:
bool load_file(const char* in_file, hmap hashtable[]) {
for(int x = 0; x < HASH_SIZE; x++) {
hashtable[x] = NULL;
}
FILE *fptr = fopen(in_file, "r");
char c[LENGTH] = "";
c[0] = '\0';
while (fgets(c, sizeof(c)-1, fptr) != NULL) {
node *n = malloc(sizeof(node));
hmap new_node = n;
new_node->next = NULL;
strncpy(new_node->content, c, LENGTH-1);
// do stuff to put it into the hashtable
}
fclose(fptr);
return true;
}
第二个检查给定的内容是否在哈希图中:
bool check_content(const char* content, hmap hashtable[]) {
char c_content[LENGTH] = "";
strncpy(c_content, content, LENGTH-1);
// do stuff to check if it's in the hashmap
return false;
}
和第三个解析给定文件并检查其内容是否在哈希图中:
int check_file(FILE* fp, hmap hashtable[], char * not_found[]) {
int num_not_found = 0;
char c[1000] = "";
while (fgets(c, sizeof(c)-1, fp) != NULL) {
char * pch;
char curToken[LENGTH] = "";
pch = strtok (c," ");
strncpy(curToken, pch, LENGTH-1);
curToken[LENGTH]=0;
if(!check_content(curToken, hashtable)) {
not_found[num_not_found] = malloc(LENGTH*sizeof(not_found[num_not_found]));
strncpy(not_found[num_not_found], curToken, LENGTH-1);
num_not_found++;
}
}
fclose(fp);
return num_not_found;
}
最后,main调用这些并释放malloc:
int main (int argc, char *argv[])
{
hmap hashtable[HASH_SIZE];
load_file(argv[2], hashtable);
FILE *fptr = fopen(argv[1], "r");
char * not_found[MAX_ENTRIES];
int num_not_found = check_file(fptr, hashtable, not_found);
for(int x=0; x<num_not_found; x++) {
free(not_found[x]);
}
for(int y=0; hashtable[y] != NULL; y++) {
free(hashtable[y]);
}
return 0;
}
我的问题是:对于这三个代码段,我做了什么导致缓冲区溢出的操作?提前非常感谢!
我终于摆脱了缓冲区溢出的问题,主要是通过在注释中遵循David的建议,再加上确定我的malloc比我需要的多。修复程序是:
new_node->next
需要一个mallocnew_node->next
的malloc仅在实际使用时才应发生。not_found[num_not_found] = malloc(LENGTH*sizeof(not_found[num_not_found]));
是错误的,应该是notfound[num_not_found] = malloc(sizeof(char) * (strlen(pch)+1))
(假设pch不是null终止的)。 (请注意,无论出于何种原因,在我的计算机上,malloc(sizeof(char) * strlen(pch)+1)
与malloc(strlen(pch)+1)
不同)