STL vector containing vector causing segfault - c++

The following code causes a segfault when I try to issue my push_back call. What am I doing wrong?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
std::string * foo = new std::string("hello world");
cout << *foo << endl;
std::vector<std::vector<std::string *> > my_vecs;
my_vecs[0].push_back(foo); // segfaults
cout << "trying to print my_vecs size of " << my_vecs.size() << " but we never reach that point due to segfault " << endl;
return 0;
}
I'm pretty sure I'm violating one of the contracts for using vector, as the problem is surely not with the STL implementation.

When you create my_vecs it has 0 elements, hence my_vecs[0] does not exists and gives segfault. You have to first reserve at least one element of my_vecs and then you can insert in the vector my_vecs[0] your pointer:
std::vector<std::vector<std::string *> > my_vecs(1);
my_vecs[0].push_back(&foo);

The outer vector must first be explicitly grown, before one can push to its elements.
This may be a little surprising since STL map's automatically insert their keys. But, it's certainly the way it is.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
const int DESIRED_VECTOR_SIZE = 1;
std::string * foo = new std::string("hello world");
cout << *foo << endl;
std::vector<std::vector<std::string *> > my_vecs;
for (int i = 0; i < DESIRED_VECTOR_SIZE; ++i) {
std::vector<std::string *> tmp;
my_vecs.push_back(tmp); // will invoke copy constructor, which seems unfortunate but meh
}
my_vecs[0].push_back(foo); // segfaults
cout << "now able to print my_vecs size of " << my_vecs.size() << endl;
return 0;
}

Related

vector with reinterpret_cast

The following code inserts only one value to the vector col.
The code is extracted from DBMS code base (for importing files), specifically, it is from 1
The code uses void* to be able to read any field type (int, float, and so on).
#include <iostream>
#include <vector>
using namespace std;
void add(std::vector<void*> &col){
reinterpret_cast<std::vector<int>&>(col).push_back( 1);
reinterpret_cast<std::vector<int>&>(col).push_back( 2);
reinterpret_cast<std::vector<int>&>(col).push_back( 13);
}
int main() {
std::vector<void*> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout <<reinterpret_cast<std::vector<int>&> (col)[i] <<endl;
return 0;
}
I am not sure how this code work?
Your code is exhibiting undefined behavior.
std::vector<void*> and std::vector<int> are two completely separate and unrelated types, you can't safely cast between them the way you are, especially since there is no guarantee that void* and int are the same byte size.
Cast the values you are pushing, don't cast the vector itself, eg:
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
void add(std::vector<void*> &col) {
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(1)));
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(2)));
col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(13)));
}
int main() {
std::vector<void*> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout << reinterpret_cast<intptr_t>(col[i]) << endl;
return 0;
}
Of course, you really should be using the proper container type to begin with:
#include <iostream>
#include <vector>
using namespace std;
void add(std::vector<int> &col) {
col.push_back(1);
col.push_back(2);
col.push_back(13);
}
int main() {
std::vector<int> col;
add(col);
cout << col.size() << endl;
for(int i=0;i<col.size();i++)
cout << col[i] << endl;
return 0;
}

c++ multiple smart pointers allocation cause crash

The maxPointers value may need to be different for your system, but allocating many unique_ptrs causes this application to crash and burn. Removing the definition of s and the cin operation gives some more room for pointer allocation.
Using MSVC 2015.
So, why does it crash and how to avoid it?
Thanks.
#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;
int main(int argn, const char*argv[])
{
int maxPointers = 37900;
vector<unique_ptr<string>> pointerHolder;
for (int i = 0; i < maxPointers; i++)
{
pointerHolder.push_back(make_unique<string>("pointer " + i));
}
cout << "done creating "<< maxPointers << " pointers" << endl;
string s;
cin >> s;
for (int i = 0; i < maxPointers; i++)
{
pointerHolder.at(i).release();
}
pointerHolder.clear();
cout << "done releasing " << maxPointers << " pointers" << endl;
return EXIT_SUCCESS;
}
The crash you encounter is because you build strings from garbage that results from call "pointer " + i. If you intend to concatenate literal "pointer" with an integer, then you'd need to convert that integer to std::string with std::to_string first:
make_unique<string>("pointer " + to_string(i));
// ~~~~~~~~~~~^

try to understand the pointers maintained by a string object

Ran a simple program to test the pointer in string object, got
0x1875028
Hello
0x1875058 0x1875028
Hello world!!!
0x1875028
I am trying to understand why would s.c_str() change value after erase() call but not st.c_str().
Here is the simple code:
#include <vector>
#include <unordered_map>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
string st;
void dum() {
string s("Hello world!!!");
printf("%p\n", s.c_str());
st = s;
s.erase(6);
cout << s << endl;
printf("%p %p\n", s.c_str(), st.c_str());
}
int main(int argc,char *argv[]) {
dum();
cout << st << endl;
st.erase(6);
printf("%p\n", st.c_str());
return 0;
}
This actually depends on the version you're using. See, for example Is std::string refcounted in GCC 4.x / C++11?. When you write for two strings, a, and b
a = b;
Then there's a question of whether they're internally pointing to the same object (up until one of them is modified). So either behavior your program exhibits is not very surprising.
First of all, I think this goes under the implementation details umbrella.
I tried that with VS2013.
After you call erase(), the string pointer returned by c_str() is not changed because I think the internal string implementation just updates the end of string (changing some internal data member), instead of doing a new heap reallocation for the internal string buffer (such an operation would likely return a new pointer value).
This is a behavior that I noted both for your local s string and the global st string.
Note that the STL implementation that comes with VS2013 doesn't use COW (COW seems to be non-standard C++11 compliant), so when you copy the strings with st = s, you are doing a deep copy, so the two strings are completely independent and they point to different memory buffers storing their respective string contents. So, when you erase something from one string, this operation is in no way reflected to the other copied string.
Sample Code
#include <iostream>
#include <string>
using namespace std;
// Helper function to print string's c_str() pointer using cout
inline const void * StringPtr(const string& str)
{
// We need a const void* to make cout print a pointer value;
// since const char* is interpreted as string.
//
// See for example:
// How to simulate printf's %p format when using std::cout?
// http://stackoverflow.com/q/5657123/1629821
//
return static_cast<const void *>(str.c_str());
}
string st;
void f() {
string s{"Hello world!!!"};
cout << "s.c_str() = " << StringPtr(s) << '\n';
st = s;
s.erase(6);
cout << s << '\n';
cout << "s.c_str() = " << StringPtr(s)
<< "; st.c_str() = " << StringPtr(st) << '\n';
}
int main() {
f();
cout << st << endl;
st.erase(6);
cout << "st.c_str() = " << StringPtr(st) << '\n';
}
Output
C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp
test.cpp
C:\Temp\CppTests>test.exe
s.c_str() = 0036FE18
Hello
s.c_str() = 0036FE18; st.c_str() = 01009A40
Hello world!!!
st.c_str() = 01009A40

Cannot push C style strings into std::vector

I'm trying to push some const char* into a vector, but the vector remains unpopulated after performing the operations I would presume to fill it.
Here's my attempt, where dict is my command-line argument.
test.cc
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<const char*> dictionary;
string line;
getline(dict, line);
while(!dict.fail()) {
dictionary.push_back(line.c_str());
getline(dict, line);
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}
dict
Hello
World
Foo
Bar
After compiling this, I get the following output:
dictionary[0] is
dictionary[1] is
dictionary[2] is
dictionary[3] is
However, if I change the dictionary's type to vector and push back line instead of line.c_str(), I get the expected output:
dictionary[0] is Hello
dictionary[1] is World
dictionary[2] is Foo
dictionary[3] is Bar
I'm not terribly familiar with C style strings, so maybe it has something to do with null termination?
You are storing dangling pointers.
std::string::c_str() isn't a pointer to some permanent copy of data — just think, that would be leaked!
Store the std::strings instead.
Your code invokes undefined behavior, because after you do
dictionary.push_back(line.c_str());
On the next line that pointer may get deleted:
getline(dict, line); // line now is a different string
You are pushing into the dictionary pointers that point to the same address and at the last iteration it fills the memory area with an empty string. If you don't care about memory leakage you can try like this:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<char *> dictionary;
while(!dict.fail()) {
string * line = new string();
getline(dict, *line);
if(line->length()>0)
{
dictionary.push_back((char *)line->c_str());
}
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}

Checking if vector 'space' in vector<vector<queue<msg>>> is empty

I am playing around with containers, and at the moment trying to use a vector<vector<queue<int>>>. The form of this container is such that the 'first' vector's index is client ID, 'second' vector's index is priority level. i.e. a message of type int is pushed into a queue of certain priority, belonging to a certain client.
I am trying to find an easy way to find out if a client has any messages i.e. if any of it's priority levels has a non-empty queue. I used this simple piece of code to illustrate what I am trying to do:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main()
{
vector<vector<queue<int>>> node_pri_msg;
queue<int> pri_msg;
node_pri_msg.resize(2);
node_pri_msg[1].resize(2);
node_pri_msg[0].resize(2);
for (int i=0; i<2; i++)
{
node_pri_msg[i].push_back(pri_msg);
}
node_pri_msg[0][1].push(3);
if (node_pri_msg[1].empty())
{
cout << "empty-check succeeded" << endl;
}
}
but it does not work i.e. it seems to think that the node_pri_msg[1] is non-empty, though there are no messages in any of the queues 'belonging' to it. Is there an easy way to do this?
I think you would be better served with this:
#include <iostream>
#include <queue>
#include <map>
using namespace std;
int main()
{
typedef std::queue<int> MessageQueue;
typedef std::map<int, MessageQueue> PriorityMap;
typedef std::map<int, PriorityMap> ClientMap;
ClientMap clients;
clients[10][1].push(1);
clients[10][1].push(2);
clients[11][2].push(3);
cout << boolalpha;
cout << clients[1].empty() << endl;
cout << clients[10].empty() << endl;
cout << clients[10][0].empty() << endl;
cout << clients[10][1].empty() << endl;
cout << clients[10][1].size() << endl;
return 0;
}
Output
true
false
true
false
2