This is my function called trim which strips a string of its quotes:
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
}
Now I am reading from a json::value object, converting the value to a string using toStyledString() and then converting that to a const char* using c_str(). I find this string has quotes around it, so I pass this value to the function trim. When the value returns the returned string is cut by two characters in the end. This is main where I think the problem lies:
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";
}
Is there a memory leak somewhere or some other detail I am overlooking ? Some help would be much appreciated. Thanks