crandom41 crandom41 - 2 months ago 7
C++ Question

Vector Data Loss When Leaving A Loop

I wouldn't consider myself a programming newbie, but I have been struggling to understand vectors for the better part of six months now.

I've tried to use vectors in "production" code, but it never seems to function how I would expect. This example is one of the many problems I have with them, as is stated in the title, Vectors seem to mysteriously lose data after leaving a while loop. This will probably boil down to I'm simply using the vector all wrong, but I would like to think my process is at least somewhat sound. As you will notice, this is a vector of objects, which is probably pivotal to the issue as well.

In this example I've made, a char pointer with a random character inside of it is added to the vector, exactly ten times. Each time, the contents of the char pointer are erased and new content is added to ensure the data is unique. After leaving the loop, and starting another to print out the contents of the vector, none of the data that was just added to the vector is there anymore. Why?

Additionally, the initialization of the vector is non-standard from the examples I've seen, but seems to be the only way to get the vector to work without crashes.

Apologies for my poor formatting, the style in the code-block is not exactly how I format the code (Bracket spacing was screwed up slightly) Thanks in advance!

#include <stdio.h>
#include <vector>
#include <stdlib.h>



int main( int argc, char * argv[ ] ) {

std::vector<char *> avector( 0 );
avector.reserve( 400 );
int counter = 0;
char * place;
bool ok;

Back:
if( counter == 10 ) {
counter = 0;
while( counter != 10 ){
printf( "Element %d: %s\n", counter, avector.at( counter ) );
++counter
}
ok = false;
}
while( counter != 10 ) {
ok = true;
place = (char *)malloc( 10 * sizeof( char ) );
*place = (char)( ( rand( ) % 26 ) + 65 );
printf("Pre-placement, element %d: %s\n", counter, place );
avector.push_back( place );
printf("Post-placement element %d: %s\n", counter, avector.at( counter ) );
free( place );
++counter;

}
if( ok == true ) {
goto Back;
}


exit( 0 );
}

Answer

place = (char *)malloc( 10 * sizeof( char ) );
You're allocating data with malloc

avector.push_back( place );
You're pushing it to the vector

free( place );
And then, you delete it. So, the pointer is still in the vector, but the memory address does not belong anymore to you.

Also, you are programming in C++, not C, so don't use printf, goto, malloc and free.
And try to not use new and delete, use smart pointers instead (C++11)