[英]Program crashes when freeing memory inside the structure
I have file parsing program which is like this, my program crashes when freeing memory.我有这样的文件解析程序,我的程序在释放内存时崩溃。 I have to check if the value is empty then i have to free the other malloced variable.
我必须检查该值是否为空,然后我必须释放另一个 malloced 变量。
struct db_handle_st {
char *server;
char *user;
};
int main()
{
char srv_conf_file[] = "C:\\\\Users\\admin\\Documents\\Visual Studio 2010\\Projects\\abcd\\abcd\\service.config";
FILE *fp = NULL;
db_handle_st db_details;
fp = fopen(srv_conf_file, "r");
if (fp != NULL) {
/* Look for key value pairs. */
while (fgets(line, sizeof(line), fp) != NULL) {
/* Get key */
key = line;
key[strlen(key) - 1] = '\0'; /* trim the newline. */
if ((value = strstr(line, "=")) != NULL) {
*value = '\0';
value++;
}
if (key && value)
printf(" %s: %s\n", key, value);
else
continue;
if (!strncmp(key, "SERVER", strlen("SERVER"))&&(strcmp(value,""))) {
/* if(strcmp(value,"")==0) {
goto err;
}*/
db_details.server = (char *)malloc(strlen(value)+1);
strcpy(db_details.server, value);
printf("db_details.server is %s\n",db_details.server);
}
if (!strncmp(key, "USER", strlen("USER"))&&(strcmp(value,""))) {
db_details.user = (char *)malloc(strlen(value)+1);
strcpy(db_details.user, value);
printf("db_details.user is %s\n",db_details.user);
}
}
}
if((db_details.user!=NULL) || (db_details.server!=NULL)) {
printf("something is zero\n");
if(db_details.user) {
free(db_details.user);}
if(db_details.server) {
free(db_details.server);}
}
}
My config looks like this我的配置看起来像这样
SERVER=localhost
USER=
When i run this program i get the当我运行这个程序时,我得到
"something is zero" and the program crashes.
“某事为零”并且程序崩溃。
You need to initialize the char pointers in the struct db_handle_st
to NULL otherwise you might free some random data (their value is undefined otherwise) and this will cause the crash.您需要将
struct db_handle_st
的字符指针初始化为 NULL,否则您可能会释放一些随机数据(否则它们的值未定义),这将导致崩溃。
PS: You do not need to check for NULL
before calling free
( free
on NULL
just does nothing) also you should fclose
the file you opened. PS:你并不需要检查
NULL
之前调用free
( free
的NULL
只是什么都不做),你也应该fclose
你打开的文件。
You never initialized db_handle_st db_details;
你从未初始化
db_handle_st db_details;
so the pointers are indeterminate, and the crash indicates that the indeterminate value was not a null pointer.所以指针是不确定的,崩溃表明不确定的值不是空指针。
Use:用:
db_handle_st db_details = { 0, 0 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.