Concurrent write to std::vector to different indices causes crash? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a big vector and i want to update some data in that vector (no insert/delete, but rather replacing an element with another on a specified index).
I was thinking that this is pretty clever to do the work on 2 or more different threads, therefore improving the speed. And since no synchronization is really necessary in this case, due to different indices this should be really fast.
Unfortunately my code crashes, either by stating: EXC_BAD_ACCESS, or "pointer being freed was not allocated".
The pseudocode:
// I have an entries_ vector with data of type DataT
std::vector<std::thread> workers(NUMBER_OF_PARALLEL_CHUNKS);
unsigned long tuplesPerChunk = entries_.size() / NUMBER_OF_PARALLEL_CHUNKS;
for (int j = 0; j < NUMBER_OF_PARALLEL_CHUNKS; ++j) {
unsigned long offset = tuplesPerChunk * j;
workers.emplace_back(std::thread([&offset, &tuplesPerChunk, this](){
for (int i = 0; i < tuplesPerChunk; ++i) {
unsigned long offsetIndex = offset + i;
entries_[offsetIndex] = createNewDataForSomeParticularReason();
}
}));
}
for (auto &worker : workers) {
if (worker.joinable()) worker.join();
}

Capture offset by value, else you have dangling pointer.
Your threads live from inside the loop until the join.
offset only lives inside one loop iteration.

Related

Why am I getting segmentation fault error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am writing a C ++ program that needs to convert numbers from decimal to binary. Here is my code:
int* convertToBinary(int i, unsigned int n) {
int ans[10000];
if (n / 2 != 0) {
convertToBinary(i + 1, n / 2);
}
ans[i] = n / 2;
return ans;
}
void send_number(int num) {
for (int j = 0; j < 16; j++) {
printf("%d", convertToBinary(0, num)[j]);
}
}
In this case, the num variable takes only natural values from 0 to 65535.
The main function is send_number().
On execution I get the 'Segmentation fault (core dumped)' error. I can't figure out why this is happening.
PS: I am C++ beginner. I don't know English well and use google translator
There are 2 issues at play - scope and (related) dangling pointers.
When you define any variable inside a function - it is only valid inside that function.
convertToBinary returns a pointer that refers to invalid memory. So when you try to print it - you are using
convertToBinary(0, num)[j]
Think about what this does. You take an invalid pointer returned by the function and add an offset j to it.

Why threads doesn't accept this input? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was doing a project that uses threads to sum some matrix but at the time of creating the threads and adding the params it always shows up the same error. Any ideas?
void sum(std::vector <double>& matrix, std::vector <double>& other) {
for (auto i = 0; i < 15; i++) {
matrix[i] += other[i];
}
}
here it is the operation that threads should do.
std::vector <double>* mat1 = new std::vector <double>[15];
std::vector <double>* mat2 = new std::vector <double>[15];
std::vector <std::thread*> threads;
for (int j = 0; j < 15; j++) {
sum(mat1[j], mat2[j]); //this works;
threads.push_back(new std::thread(sum,mat1[j],mat2[j])); //this dont why?;
}
Thanks in advance
To get it to compile, change:
std::thread(sum,mat1[j],mat2[j])
to:
std::thread(sum, std::ref(mat1[j]), std::ref(mat2[j]))
Example: https://godbolt.org/z/Ek-cnm
But there are multiple problems with your question and code besides just getting it to compile, please listen to what other have said in the comments.

Declare int variable aux a.length = (); Or use o.length () in all loops? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I wonder which is faster: Say I'm working with some text (30 characters), which would be better? And with a lot of text which would be better?
1-
int tam = text.length();
for(int i=0;i<tam;i++)
{
//something here//
}
2-
for(int i=0;i<a.length();i++)
{
//something here//
}
and also comparing these two:
1-
for (int i = 0; i < b.length(); i++)
{
aux = a.find(b[i]);
if (aux == -1)
{
sucess = 0;
break;
}
else
{
a.erase(aux,1);
}
}
2-
for (int i = 0; i < b.length(); i++)
{
if (a.find(b[i]) == -1)
{
sucess = 0;
break;
}
else
{
a.erase(a.find(b[i]),1);
}
}
Both first are the better approach.
On the first example you are checking if i<a.length() is true on every cycle. That means that you are going to execute a.length() for every iteration. If the variable a is not changed, it is unnecessary and the better approach is to calculate before and use that value.
Note that if the variable a is changed inside, placing i<a.length() might be the correct approach. It depends on your problem.
On the second example it is the same basics. You avoid useless calculations because you won't need to calculate a.find(b[i]) again inside the else.
As a general rule of thumb, as computations get bigger, more complex, and more frequent you want to minimize your unnecessary calculations. This means that storing something that needs to be calculated in a variable may speed up the process.
In both of your examples, for extremely large numbers,
int scratch = big.length();
for(int i=0;i<scratch;i++){
//body//
}
is usually faster.
In the future, general questions like this tend to belong in something like the Code Review Stack Exchange.

Unexpected changing of C++ constant integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

For loop variable going to hell for seemingly no reason? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.
The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:
void enterdata(float dpoint,int num){
autodata[num] += dpoint;
}
float autocorr(){
float autocorrelation = 0;
for(int a = 0; a<SIZEX; a++)
{
for(int b = 0; b<SIZEY; b++)
{
if(grid[a][b] == reference[a][b]){autocorrelation++;}
}
}
autocorrelation /= SIZEX*SIZEY;
autocorrelation -= 0.333333333333;
return autocorrelation;
}
for (long z = 0.0; z<MAXTIME; z++)
{
for (long k=0; k<TIMESTEP; k++)
{
grid.pairswap();
}
if (z == autostart_time)
{
grid.getreference();
signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
}
if ((z*10)%dataint == 0)
{
if (signal == 1) {
//!!! this is the important segment!!!
cout << z << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}
From the "important segment" marked in the code, this is my output:
3200 before,
1059760811 after,
0.666667 (number returned by function)
Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.
I have no idea how to fix this, or what is going on. Help?!?!?
Thanks!
Looks like you may have a Stack Overflow issue in your enterdata function.
Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.
#WhozCraig is right, a stack overwrite by a called function seems the most likely explanation.
You should be able to find out in your debugger how to break on any change to the memory at address of z, this will quickly provide an exact diagnosis.
For Visual Studio (for example), see here.