c - 释放结构内的内存时程序崩溃

标签 c struct malloc free

我有这样的文件解析程序,我的程序在释放内存时崩溃。我必须检查该值是否为空,然后我必须释放其他 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);}
    }
}

我的配置如下

SERVER=localhost
USER=

当我运行这个程序时,我得到

"something is zero" and the program crashes.

最佳答案

您需要将struct db_handle_st中的字符指针初始化为NULL,否则您可能会释放一些随机数据(否则它们的值未定义),这将导致崩溃。

PS:在调用 free 之前,您不需要检查 NULL (free on NULL 只是做什么也没有)您还应该fclose您打开的文件。

关于c - 释放结构内的内存时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33068180/

相关文章:

c++ - 与 C++ 相比, native C 中的复数(和虚数 i)如何表示?

c - 删除列表时head如何连接到tail

c - 为什么 sizeof run on struct 必须有括号

c - Typedef 结构问题

c - (*prt)[N][N] 在处理堆分配内存时如何工作?

C:访问另一个文件中的数组会产生段错误

c - 动态读取和存储到 char 数组

c - 使用 epoll 在客户端监听不同的多播套接字

c - 如果 posix 关闭调用失败怎么办?

用 C 编写网站?