【问题标题】:Copy a const char * into a char **将 const char * 复制到 char **
【发布时间】:2015-11-21 10:39:42
【问题描述】:

我正在使用libconfig 库从文件中读取一些配置数据。我无法提取用于解析信息和事后清理的功能。

运行strcpy(*hostname, tmp) 会导致核心转储。

hostnameportip 被初始化为 NULL

int parseConfig(char **hostname, char **port, char **ip) {

    config_t cfg, *cf;
    const char *tmp;

    cf = &cfg;
    config_init(cf);

    if(!config_read_file(cf, CONFIG)) {
        fprintf(stderr, "%s:%d - %s\n",
            config_error_file(cf),
            config_error_line(cf),
            config_error_text(cf));
        config_destroy(cf);
        return(EXIT_FAILURE);
    }

    config_lookup_string(cf, "hostname",  &tmp);
    strcpy(*hostname, tmp);
    config_lookup_string(cf, "ip", &tmp);
    strcpy(*ip, tmp);
    config_lookup_string(cf, "port", &tmp);
    strcpy(*port, tmp);

    config_destroy(cf);

    return(EXIT_SUCCESS);
}

【问题讨论】:

  • parseConfig 怎么称呼?您编译时是否包含所有警告和调试信息 (gcc -Wall -Wextra -g)?您是否使用了调试器 (gdb)? valgrind ?
  • 最好为主机名而不是**主机名提供一个最大大小的数组,这样当你的函数用户提供一个太小的缓冲区时,他不会感到惊讶。例如字符主机名[100]; parseConfig(char* hostName, int maxLenHostName, ...);

标签: c libconfig


【解决方案1】:

由于它们被初始化为NULL,你应该为它们分配足够的内存空间。

config_lookup_string(cf, "hostname",  &tmp);
*hostname = malloc(strlen(tmp)+1);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = malloc(strlen(tmp)+1);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
*port = malloc(strlen(tmp)+1);
strcpy(*port, tmp);

或者,如果您有 strdup() 可用,

config_lookup_string(cf, "hostname",  &tmp);
*hostname = strdup(tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = strdup(tmp);
config_lookup_string(cf, "port", &tmp);
*port = strdup(tmp);

【讨论】:

    【解决方案2】:

    切断中间人。

    config_lookup_string(cf, "hostname",  hostname);
    

    这要求您永远不要破坏cfg,因为它拥有为配置字符串分配的内存。

    static config_t cfg;
    config_t *cf;
    
    // config_destroy(cf); <-- don't!
    

    如果每次程序运行只读取一次配置,这应该不是问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 2013-11-09
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      相关资源
      最近更新 更多