C++如何读取文件行存入char指针避免指向已失效变量
解决方案
方案1:优先推荐,修改结构体使用std::string管理字符串
这是最符合C++开发规范的实现,无需手动管理内存,可完全规避你遇到的两个问题:
#include <string> struct connection_details { std::string server, user, password, database, mysql_port, ssh_port; };
对应的读取函数修改如下:
#include <fstream> #include <string> void get_config(const std::string &config_path, connection_details *mysql) { std::ifstream file(config_path); std::string str; std::getline(file, str); mysql->user = str; std::getline(file, str); mysql->server = str; std::getline(file, str); mysql->database = str; // 剩余字段按同样规则赋值 file.close(); }
std::string的赋值操作会独立拷贝字符串内容,每个结构体成员持有独立的内存空间,且生命周期和结构体实例绑定,不会出现局部变量销毁导致的野指针问题。
方案2:必须保留const char*结构体成员的实现
如果因为对接C接口等原因不能修改结构体定义,可以手动在堆上分配独立内存存储每个字符串:
#include <fstream> #include <string> #include <cstring> void get_config(const std::string &config_path, connection_details *mysql) { std::ifstream file(config_path); std::string str; std::getline(file, str); mysql->user = strdup(str.c_str()); std::getline(file, str); mysql->server = strdup(str.c_str()); std::getline(file, str); mysql->database = strdup(str.c_str()); // 剩余字段按同样规则赋值 file.close(); }
注意:使用
strdup分配的内存需要手动释放,在结构体实例使用完毕后,需要逐个free所有const char*成员,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Alexander Minor
相关产品推荐
相关产品推荐

