0

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

NikhilBanerjee
  • 73
  • 1
  • 11

1 Answers1

2

First, you declare a local variable:

char c_store[c_length-2]; // Removing two for the quotes 

Then, you copy pointer to allocated memory (not its contents!):

const char * c_trimmed = c_store;

Now c_trimmed points to the same space in memory as c_store does. Then you print it:

cout<<c_trimmed;     // Prints the string CORRECTLY here !!

Then you return it from function:

return c_trimmed;    

And then the memory pointed to by c_trimmed and c_store is automatically freed:

}

After returning from function, its result no longer points to valid place in memory. If you want return a c-style string from function, you have to allocate memory for it. Something like:

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

Bottom note. If you really write in C++ and not in C, use std::string instead - you'll have half of the problems you have now (and will have in future).

Spook
  • 25,318
  • 18
  • 90
  • 167
  • Ah I see, the local variables scope finished at the end of the trim function, thus new memory must be allocated to the pointer thats being returned. Thanks a ton Spook – NikhilBanerjee Dec 24 '13 at 07:45
  • Is it because memory is automatically added to std::string? Yes okay I m using a weird mix of C and C++ at the moment because most of the external libraries that I m using for my program are written in C. – NikhilBanerjee Dec 24 '13 at 07:50
  • `std::string` takes care of memory operations. For instance, if you simply return a local `std::string` from the function, it will automatically copy or move data (depending on C++ version you use) to the outer instance, such that you won't have to worry about the variable scope. Also, `std::string` operations are a lot easier to perform, safer (you *usually* don't even have much chance to leak memory or work on invalid one) and sometimes even a little faster than in case of C-style strings. I strongly advice using std classes if you write code in C++. – Spook Dec 24 '13 at 07:53