[英]How to avoid buffer overflow with C struct array of strings
我在讀取 C 中的文件並復制字符 arrays 時遇到緩沖區溢出。 有三段可能有問題的代碼,我不知道哪里出錯了。
第一個讀取文件並將其填充到 hashmap 中:
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;
}
第二個檢查給定內容是否在 hashmap 中:
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;
}
第三個解析給定文件並檢查其內容是否在 hashmap 中:
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)
不同)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.