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.
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.
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.
You never initialized 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 };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.