这是我的名为trim的函数,它删除了一串引号:
const char* trim(const char* c) {
const char *pos = c;
//Getting the length of the string
int c_length = 0;
while (*pos != '\0') {
c_length++;
pos++;
}
cout<<"\nThis is the length of string:"<<c_length;
char c_store[c_length-2]; // Removing two for the quotes
pos = c;
const char* quote = "\"";
char ch;
int i;
for (i = 0; *pos != '\0'; pos++){
ch = (char)*pos;
if(ch!=*quote) {
c_store[i] = (char)*pos;
i++;
}
}
c_store[i]='\0'; // Adding the null terminating character
const char * c_trimmed = c_store;
cout<<c_trimmed; // Prints the string CORRECTLY here !!
return c_trimmed; // There is problem when it returns, see main
}
现在我正在读取json :: value对象,使用toStyledString()将值转换为字符串,然后使用c_str()将其转换为const char *。我发现这个字符串有引号,所以我把这个值传递给函数trim。当值返回时,返回的字符串最后会被两个字符剪切掉。这是我认为问题所在的主要原因:
int main(int argc, char** argv) {
// Reading json config file into a Json::Value type
char* config_file = read_file_into_string(argv[1]);
Json::Value Bootloading_config = create_json_object(config_file);
const char* bucket_name_json = Bootloading_config["Bootloading"]["bucket_name"].toStyledString().c_str(); // Storing value from json
const char* bucket_name_trimmed = trim(bucket_name_json); // Using trim function
const char* bucket_name = "nikhil-hax"; // Assigning another pointer for comparison
printf("\n Trimmed bucket_name:%s", bucket_name_trimmed); // It is printing the string with the last two chars cut out
if(strcmp(bucket_name_trimmed,bucket_name) == 0) // To check
cout<<"\nTRIM function Worked!!";
else cout<<"\nNOT working, look closer";
}
某处有内存泄漏还是我忽视的其他细节?一些帮助将非常感激。感谢
答案 0 :(得分:2)
首先,声明一个局部变量:
char c_store[c_length-2]; // Removing two for the quotes
然后,将指针复制到已分配的内存(而不是其内容!):
const char * c_trimmed = c_store;
现在c_trimmed
指向内存中与c_store
相同的空间。然后你打印它:
cout<<c_trimmed; // Prints the string CORRECTLY here !!
然后从函数返回它:
return c_trimmed;
然后c_trimmed
和c_store
指向的内存会自动释放:
}
从函数返回后,其结果不再指向内存中的有效位置。如果要从函数返回c样式的字符串,则必须为其分配内存。类似的东西:
char * c_trimmed = new char[c_length-2];
strcpy(c_trimmed, c_store);
return c_trimmed;
// Don't forget to delete[] the result of this function when it is no longer needed
// or else you'll end up with memory leak
底部注释。如果真的用C ++编写而不是用C语言编写,请使用std::string
代替 - 你现在已经有了一半的问题(以后会有问题)。