[英]Memory Leaks when Tokenizing a String
我用 C 編寫了一個程序來標記輸入字符串,當用戶輸入“exit”時,它退出程序。
它正確地標記了字符串,但是,當我使用 valgrind 測試我的程序時,出現了一些內存泄漏。 唯一沒有發生內存泄漏的情況是在編譯然后執行之后,我立即退出。
這是 valgrind 的輸出: Valgrind Memory Leaks
這是我的程序代碼:
int main() {
/* Main Function Variables */
char *buf;
char *savecpy = NULL;
char *token;
size_t num_chars;
size_t bufsize = 2048;
int run = 1;
int tok_count = 0;
int cmp;
/* Allocate memory for the input buffer. */
buf = (char *) malloc(sizeof(char) * bufsize);
/*main run loop*/
while(run) {
/* Print >>> then get the input string */
printf(">>> ");
num_chars = getline(&buf, &bufsize, stdin);
cmp = strcmp(buf, "exit\n");
if (num_chars > 1) {
/* Tokenize the input string */
if (cmp != 0) {
/* Display each token */
savecpy = strdup(buf);
while((token = strtok_r(savecpy, " ", &savecpy))) {
printf("T%d: %s\n", tok_count, token);
tok_count++;
}
}
/* If the user entered <exit> then exit the loop */
else {
run = 0;
break;
}
}
tok_count = 0;
}
/*Free the allocated memory*/
free(buf);
return 1;
}
導致 valgrind 內存泄漏的問題可能是什么? 我正在為我的輸入字符串釋放內存,但我仍然遇到內存泄漏。
savecpy
應該被釋放。 如手冊中所示:
新字符串的內存通過 malloc(3) 獲得,並且可以通過 free(3) 釋放。
savecpy
在通過strtok_r
第三個參數后不能被釋放,因為這個函數修改了指針。 而是通過這樣的事情
char* ptr;
strtok_r(..,.., &ptr);
然后你可以免費savecpy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.