Problem pushing char* to vector, but after each iteration its adding a pointer to the same values buffer into the vector

Viewed 318

[SOLVED] I changed the char variables to a std::string array, where I push float variables to the array. After all this you can convert the std::string to a const char*

I'm making client to a server. And I want to send data to the server, but when I run this code I am getting 4.5 twice instead of 180 & 4.5. I am using chars, because the send function that I am using only supports chars.

Emptying the char (doesn't work) Printed the value before the if statement ends (This shows that the value is correct), but when the for loop loops the second time it is 4.5 instead of 180.

float an = 180;
float dis = 4.5;

for (int i = 0; i < 1; i++) {
    set.measurements.push_back(an); 
    set.measurements.push_back(dis);
}

for (int i = 0; i < set.measurements.size(); i++){
    sprintf(values, "%0.1f", set.measurements[i]);
    if (i == 1 && i != 0){
         std::cout << "{ 4.5 }" << '\n'; // expected output
         char *dist = new char[10];
         dist = values; // <-- Value is 4.5
         meas.push_back(dist); 
         // This is 4.5 but the angle doesn't stay 180
         delete dist;
    }
    if (i == 0 && i != 1){
        std::cout << "{ 180 }" << '\n'; // Expected output
        char *ang = new char[10];
        ang = values; // <-- Value is 180 here
        meas.push_back(ang); 
        delete ang;
    }
}

for (int i = 0; i < 2; i++) {
  std::cout << &*meas[0] << '\n';
}

I expect the output to be 180 & 4.5, but the actual output is 4.5 & 4.5

1 Answers
char *dist = new char[10];

This allocates a new char array, and sets dist to point to it.

dist = values; // <-- Value is 4.5

The next line immediately replaces the distpointer to the new-ed buffer, leaking this memory. This now sets dist to point to some other buffer (presumably), instead.

meas.push_back(dist); 

This now adds the pointer to the values object into the vector. Each iteration of the loop, therefore, ends up adding a pointer to the same values buffer into the vector, and that's what you're seeing, in the end.

delete dist;

This is still pointing to values. From the context, it is unlikely that values was originally created with new, and even if it was, each iteration of the loop will end up deleteing the same pointer. Either way, this is undefined behavior, and with enough looping, your entire program will likely crash.

The second if statement repeats all of the above bugs.

Since your intent is, apparently, to write C++ code, you should actually use the C++ library, namely the formatted output operators, and std::strings, that will correctly allocate and manage all the memory for you, eliminating these kinds of common, logical bugs.

Related