c++ - 为什么 const char* 返回的值丢失了两个字符?但是在返回之前打印正确的值

标签 c++ pointers memory-leaks

<分区>

这是我的名为 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";

}

是否存在某处内存泄漏或我忽略的其他一些细节?一些帮助将不胜感激。谢谢

最佳答案

首先,声明一个局部变量:

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_trimmedc_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 - 您现在遇到的问题只有一半(将来也会遇到) .

关于c++ - 为什么 const char* 返回的值丢失了两个字符?但是在返回之前打印正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756693/

相关文章:

c++ - std::is_same 结果与左值和右值引用

C 指针矩阵函数中的指针问题

c++ - 使用 "X11/Xutil.h"库读取像素时发生内存泄漏(使用 valgrind 输出)

java - 如果重置回调,为什么Android会由于静态Drawable而泄漏内存?

c++ - 线程在等待锁定的互斥体时会休眠吗?

c++ - 为矩阵赋值时的奇怪行为 (C/C++)

c++ - boost::multiprecision::float128 和 C++11

c++ - 如何避免-fpermissive?

c++ - 常量之间的区别。指针和引用?

mysql - pthread导致mysql内存泄漏