问题描述
我用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内存泄漏的问题吗?我正在为输入字符串释放内存,但是仍然出现内存泄漏。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)