C++: Iterate using enum type - c++

I have these codes:
for (i = 0; i <= WND_WRL; i++) {
syslog(LOG_ERR, "TESTE i=%d WND_WRL=%d", i,WND_WRL);
}
for (i = 0; i <= WND_WRL; i++) {
syslog(LOG_ERR, "OnScrDsp for i=%d WND_WRL=%d", i,WND_WRL);
m_pWnd[i] = gtk_window_new(GTK_WINDOW_POPUP);
assert(m_pWnd[i]);
}
The first for is only to explain my problem. The second is really my problem.
The source of second code can be found here:
https://github.com/HuayraLinux/intel-classmate-function-keys/blob/master/OnScrDsp.cpp
The problem:
WND_WRL variable came from
typedef enum {
WND_BRG,
WND_DSP,
WND_WRL,
} WND_ID;
struct.
In first code I can see i iterate until 2 (0,1,2) and WND_WRL will be always 2. The problem is in second code: even WND_WRL ever print 2 value, that for will iterate i until receive SIGV signal (11) and break my application (here it stop with i=384). I can understand why 384, I am not concerned about that.
What I do not understand is why the same condition provide different ways. If I change WND_WRL to number 2, I get correct code and correct app execution.
My first idea is the block of the second for maybe change WND_WRL value, but isn't happened.
I can understand if may be this code is writing in wrong memory position, but I always see WND_WRL with 2 value.
SOLUTION :
Change expression "i <=WND_WRL" to "i < WND_WRL" because m_pWnd size. It explain SIGV, but not explain why for continue until receive SIGV even if 2<=2 condition matches. Overriding memory we know can destroy a lot of things, but constants and code are read-only stack memory region, so access m_pWnd[3] and others i++ not explain why for does not stop.

Variable m_pWnd is defined in your source code as an array of pointers, with a size of 2, so valid index is 0 or 1.
GtkWidget *m_pWnd[WND_WRL];
But your loop goes i <= WND_WRL, so i=2 case will crash
m_pWnd[i] = gtk_window_new(GTK_WINDOW_POPUP);

Related

When creating threads using lambda expressions, how to give each thread its own copy of the lambda expression?

I have been working on a program that basically used brute force to work backward to find a method using a given set of operations to reach the given number. So, for example, if I gave in a set of operations +5,-7,*10,/3, and a given number say 100(*this example probably won't come up with a solution), and also a given max amount of moves to solve (let's say 8), it will attempt to come up with a use of these operations to get to 100. This part works using a single thread which I have tested in an application.
However, I wanted it to be faster and I came to multithreading. I have worked a long time to even get the lambda function to work, and after some serious debugging have realized that the solution "combo" is technically found. However, before it is tested, it is changed. I wasn't sure how this was possible considering the fact that I had thought that each thread was given its own copy of the lambda function and its variables to use.
In summary, the program starts off by parsing the information, then passes the information which is divided by the parser as paramaters into the array of an operation object(somewhat of a functor). It then uses an algorithm which generated combinations which are then executed by the operation objects. The algorithm, in simplicity, takes in the amount of operations, assigns it to a char value(each char value corresponds to an operation), then outputs a char value. It generates all possible combinations.
That is a summary of how my program works. Everything seems to be working fine and in order other than two things. There is another error which I have not added to the title because there is a way to fix it, but I am curious about alternatives. This way is also probably not good for my computer.
So, going back to the problem with the lambda expression inputted with the thread as seen is with what I saw using breakpoints in the debugger. It appeared that both threads were not generating individual combos, but more rather properly switching between the first number, but alternating combos. So, it would go 1111, 2211, rather than generating 1111, 2111.(these are generated as the previous paragraph showed, but they are done a char at a time, combined using a stringstream), but once they got out of the loop that filled the combo up, combos would get lost. It would randomly switch between the two and never test the correct combo because combinations seemed to get scrambled randomly. This I realized must have something to do with race conditions and mutual exclusion. I had thought I had avoided it all by not changing any variables changed from outside the lambda expression, but it appears like both threads are using the same lambda expression.
I want to know why this occurs, and how to make it so that I can say create an array of these expressions and assign each thread its own, or something similar to that which avoids having to deal with mutual exclusion as a whole.
Now, the other problem happens when I at the end delete my array of operation objects. The code which assigns them and the deleting code is shown below.
operation *operations[get<0>(functions)];
for (int i = 0; i < get<0>(functions); i++)
{
//creates a new object for each operation in the array and sets it to the corresponding parameter
operations[i] = new operation(parameterStrings[i]);
}
delete[] operations;
The get<0>(functions) is where the amount of functions is stored in a tuple and is the number of objects to be stored in an array. The paramterStrings is a vector in which the strings used as parameters for the constructor of the class are stored. This code results in an "Exception trace/breakpoint trap." If I use "*operations" instead I get a segmentation fault in the file where the class is defined, the first line where it says "class operation." The alternative is just to comment out the delete part, but I am pretty sure that it would be a bad idea to do so, considering the fact that it is created using the "new" operator and might cause memory leaks.
Below is the code for the lambda expression and where the corresponding code for the creation of threads. I readded code inside the lambda expression so it could be looked into to find possible causes for race conditions.
auto threadLambda = [&](int thread, char *letters, operation **operations, int beginNumber) {
int i, entry[len];
bool successfulComboFound = false;
stringstream output;
int outputNum;
for (i = 0; i < len; i++)
{
entry[i] = 0;
}
do
{
for (i = 0; i < len; i++)
{
if (i == 0)
{
output << beginNumber;
}
char numSelect = *letters + (entry[i]);
output << numSelect;
}
outputNum = stoll(output.str());
if (outputNum == 23513511)
{
cout << "strange";
}
if (outputNum != 0)
{
tuple<int, bool> outputTuple;
int previousValue = initValue;
for (int g = 0; g <= (output.str()).length(); g++)
{
operation *copyOfOperation = (operations[((int)(output.str()[g])) - 49]);
//cout << copyOfOperation->inputtedValue;
outputTuple = (*operations)->doOperation(previousValue);
previousValue = get<0>(outputTuple);
if (get<1>(outputTuple) == false)
{
break;
}
debugCheck[thread - 1] = debugCheck[thread - 1] + 1;
if (previousValue == goalValue)
{
movesToSolve = g + 1;
winCombo = outputNum;
successfulComboFound = true;
break;
}
}
//cout << output.str() << ' ';
}
if (successfulComboFound == true)
{
break;
}
output.str("0");
for (i = 0; i < len && ++entry[i] == nbletters; i++)
entry[i] = 0;
} while (i < len);
if (successfulComboFound == true)
{
comboFoundGlobal = true;
finishedThreads.push_back(true);
}
else
{
finishedThreads.push_back(true);
}
};
Threads created here :
thread *threadArray[numberOfThreads];
for (int f = 0; f < numberOfThreads; f++)
{
threadArray[f] = new thread(threadLambda, f + 1, lettersPointer, operationsPointer, ((int)(workingBeginOperations[f])) - 48);
}
If any more of the code is needed to help solve the problem, please let me know and I will edit the post to add the code. Thanks in advance for all of your help.
Your lambda object captures its arguments by reference [&], so each copy of the lambda used by a thread references the same shared objects, and so various threads race and clobber each other.
This is assuming things like movesToSolve and winCombo come from captures (it is not clear from the code, but it seems like it). winCombo is updated when a successful result is found, but another thread might immediately overwrite it right after.
So every thread is using the same data, data races abound.
You want to ensure that your lambda works only on two three types of data:
Private data
Shared, constant data
Properly synchronized mutable shared data
Generally you want to have almost everything in category 1 and 2, with as little as possible in category 3.
Category 1 is the easiest, since you can use e.g., local variables within the lambda function, or captured-by-value variables if you ensure a different lambda instance is passed to each thread.
For category 2, you can use const to ensure the relevant data isn't modified.
Finally you may need some shared global state, e.g., to indicate that a value is found. One option would be something like a single std::atomic<Result *> where when any thread finds a result, they create a new Result object and atomically compare-and-swap it into the globally visible result pointer. Other threads check this pointer for null in their run loop to see if they should bail out early (I assume that's what you want: for all threads to finish if any thread finds a result).
A more idiomatic way would be to use std::promise.

Random Symbols Getting Printed Without Initialization

I made a fairly short text-based animation program:
#include <iostream>
void animation(char words[], int sizeOfWords) {
for(int x = 0; x < sizeOfWords; x++){
for(double y = 0; y < 10000000; y++);
std::cout << words[x];
if(words[x] == '!') std::cout << std::endl;
}
}
int main() {
char words[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','T','h','i','s',' ','i','s',' ','m','y',' ','f','i','r','s','t',' ','C','+','+',' ','a','n','i','m','a','t','i','o','n','!','H','o','p','e',' ','y','o','u',' ','e','n','j','o','y','e','d','!'};
int amountOfLetters = 0;
for(unsigned x : words) amountOfLetters++;
animation(words, amountOfLetters);
}
When I first made the program I forgot to initialize int amountOfLetters; to 0. That is when I got all these random symbols. The program is fine with or without initializing it. Just without assigning 0 to it, I get these extras in the end.
Without Initialisation Of The Variable will give the following result:
Hello World!
This is my first C++ animation!
Hope you enjoyed!
!
t ht ÉH P j     T j ­Ðou2ö¤.■   Á╬ouÈ╬ouht mzou
Process returned 0 (0x0) execution time : 11.466 s
Press any key to continue.
With Initialisation Of The Variable will give the following result:
Hello World!
This is my first C++ animation!
Hope you enjoyed!
Process returned 0 (0x0) execution time : 4.444 s
Press any key to continue.
You could try running the codes yourself if you want. I would just like to know why are these symbols being printed out. If you can help i'd appreciate it. If not thanks for stopping by.
This post isn't a duplicate of Why uninitialized char array is filled with random symbols?. I talk about passing the number of elements in an array and passing them as argument, afterwards looping through them. The other post is simply just talking about initializing an array Without Information in it and printing it. Meanwhile, again, I am talking about Having Information, just the size of the array holding them was the problem. Simply theirs is about printing an array with no elements, mine is about looping through an array with elements but, mistakenly making an error for the size.
Your animation function is accessing the char array by index, until the index == sizeOfWords. If amountOfLetters is not initialised you will start incrementing a random value, and will therefore read past the end of the array in animation. That, of course, has random values.
When I first made the program I forgot to initialize int amountOfLetters; to 0. That is when I got all these random symbols. The program is fine with or without initializing it. Just without assigning 0 to it, I get these extras in the end.
That's because without initializing amountOfLetters the amountOfLetters++; operation is undefined behavior.
amountOfLetters may have an arbitrary value at the beginning of the loop, as it was left on the stack from previous operations.
Also note that you could greatly simplify and improve your code just omitting the loop and write:
animation(words, sizeof(words));

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

Why am I getting this output?

Alright so I writing Conways Game of Life in C++, and so far I have only created the rule that allows users to create cells if it has 3 neighbors.
Here is the current code: http://tinypaste.com/f59b4463
When I launched the program I entered in the coordinates so that I would have the gameboard depicted in the photo below, and the output wasn't what I expected, it should have made it so that the cell 2,1 would be alive, but in the output it remained dead. I am not sure why it is not working. Any help?
Input & Output: http://i.imgur.com/1Mvhi.png
Several things to address, and while this is not an answer, it's too big for a comment. Please fix these then I will get back to you...
In gameboard() please arrange the code so that it consists of two for loops instead of all the couts. Example:
int i, j;
for (i = j = 0; i < 10; i++) {
for (; j < 10; j++) {
cout << world[i][j];
}
}
it's much more concise.
Second, in cells(), in the second for loop, you can use another nested for loop.
Third, I would avoid naming normal variables in ALL CAPS since that is generally reserved for preprocessor #defines.
K, enjoy cleaning up :)
Alright. It's an algorithmic issue. When you call calculate, it creates extra cells because it's not exactly one generation. It's a mix of two and three - it acts on cells you just created. Get what I'm saying? I explained this on GMail.

Array over written with last value assigned?

I have a pointer to pointer array. I am assigning each row in the while loop below and the printf inside the while loop shows each is assigned my id number 1-20.
After, out side of the while loop I iterate through the array and every element is written with id 20?
Any help is greatly appreciated. (FYI- I am using the Template2doc library and example1.c, at the bottom here- http://www.algonet.se/~thunberg/template2doc/c_version/docs/index.htm)
Below code only shows problem area, I took out the rest.
char **tableData[500]={NULL};
char *myData[500][2];
while(rc == SQLITE_ROW){
tableData[r] = myData[r];
printf(*tableData[r]); <-- Displays id 1-20 fine
r=r+1;
}//end while
tableData[r+1] = NULL;//null terminated array
for (a=0; a<r; a++){
printf("\n");
printf(*tableData[a]); <--Displays 20 elements all of id 20?
}
outputFile=insertTableData(outputFile, dataMarker, fieldMarker, tableData);
You should create something that actually compiles and reproduces the problem. Not only will it help people help you, but in doing so you may very well find the problem yourself.
In your code excerpts we have no idea:
What rc is, how its value is set, or how its value is ever going to change and therefore terminate the loop
What the initial value of r is
What the actual contents of myData are
I created this code based on what you posted, which produces the same output from both loops. So either I've missed something in what you did post, or you left something important out.
int main( int argc, char** argv ) {
#define STRING char *
STRING dummy = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!##$%^&*()";
STRING *tableData[500]={0};
STRING myData[500][2];
int r=0;
while(r < 20){
myData[r][0] = dummy+2*r;
myData[r][1] = dummy+r;
tableData[r] = myData[r];
printf(*tableData[r]);
printf("\n");
r=r+1;
}//end while
int a;
for (a=0; a<r; a++){
printf(*tableData[a]);
printf("\n");
}
}
As pointed out, you are assigning Null at r+2 position. And are you in any way modifying tableData or myData in between the while and for loop?
How are you populating myData? I don't see a clear bug in the code example given, but I suspect the problem is that you are assigning a pointer to a buffer in myData without actually copying the contents, so that myData[0 .. r] all point to the same buffer, which will only store the most recent value read. Try this:
while(rc == SQLITE_ROW){
tableData[r] = myData[r];
if (r > 0)
printf(*tableData[r-1]);
r=r+1;
}//end while
That should print the ids from 1 to 19 fine. If it starts at id 2 instead of id 1, that suggests myData is not keeping a copy of the data, it's all pointing at the same location.
Well from what I can see right now, you're terminating your tableData at essentially r+2 from your last "duple" of information. Also, it might be a little clearer (maybe just for me) if you did tableData[0][1] or tableData[0][2] when printf'ing. That kind of makes it more clear that tableData is an index to a "structure" of 2, each containing a NULL terminated string. That might help with your debugging as well...
Try this for debugging then :
printf("Character at 0x%x : %d", tableData[a], *tableData[a]);
May be the bug is in what you took out ?
Yes, there were all pointing to the last value whe done. I went ahead and allocated memory space for each item, pointing to each accordingly.