Here is my code:
#include <cstdlib>
#include <stdio.h>
#define NUM_READINGS 3
int* readingsTotal;
int* readingsAverage;
int readingsIndex;
using namespace std;
void avgOf(int* toFindAvgOf, int size) {
int i;
for (i = 0; i < size; i++) {
// Add reading to total for each component.
readingsTotal[i] += toFindAvgOf[i];
// Once method has been iterated through n (NUM_READINGS) times:
if (readingsIndex == NUM_READINGS - 1) {
// Set the arithmetic mean.
readingsAverage[i] = readingsTotal[i] / NUM_READINGS;
// Reset the total.
readingsTotal[i] = 0;
}
}
readingsIndex++;
}
int iterate(int findAvgOf) {
int toFindAvgOf[] = {findAvgOf, 20, 30};
avgOf(toFindAvgOf, sizeof (toFindAvgOf));
return readingsAverage[0];
}
int main(int argc, char** argv) {
readingsTotal = (int []){0, 0, 0};
readingsAverage = (int []){0, 0, 0};
int i;
for (i = 0; i < 3; i++) {
int smthd = iterate(12 + i * 2);
printf("%d\n", smthd);
}
return 0;
}
When I run this in netbeans c/c++, it builds with now errors but when it executes it fails and prints:
RUN FAILED (exit value 1, total time: 86ms)
When I go into debug mode it also fails immediately and gives the SIGSEGV error. From reading online I'm guessing there is some issue with the way I am dereferencing a pointer. But I have no clue where exactly it is failing at. I am pretty new to c++ so any help would be great!
In C, the sizeof function returns the size of the object in bytes.
So when you say:
sizeof (toFindAvgOf)
That will return 12 (assuming an int on your system is 4-bytes) thus causing an index out of bounds condition in the avgOf function.
To get the length of the array:
sizeof(toFindAvgOf) / sizeof(int)
Related
I'm trying to do a sum of 2 matrices using pthreads in c++. I'm stuck at trying to pass the result of the sum calculated inside a thread to my main function.
The 2 values to be added are inside a struct:
struct sum{
int value1;
int value2;
int result;
}typedef struct_sum;
And the struct containing the values is passed as an argument to pthread_create() so that the operation is excuted inside a thread.
Here's my routine:
void * routine(void * sum) {
std::cout<<((struct_sum *)sum)->value1 + ((struct_sum *)sum)->value2<<std::endl;
std::cout<<((struct_sum *)sum)->value1<<std::endl;
std::cout<<((struct_sum *)sum)->value2<<std::endl;
int i = (((struct_sum *) sum)->value1 + ((struct_sum *) sum)->value2);
// memcpy(&(((struct_sum *)sum)->result), reinterpret_cast<const void *>(i), sizeof(i));
((struct_sum *)sum)->result = i;
std::cout<<&(((struct_sum *)sum)->result)<<std::endl;
pthread_exit(nullptr);
}
In the first 3 cout I check if my values are coming correctly to the thread.
In the last cout (before exiting the thread) I check the memory address of the result element of the struct (so I can see that it has the same address inside the main function).
Here's the main function:
int main(int argc, char * argv[]) {
int mat_1[ROW_SIZE][COLUMN_SIZE] = {{1, 2},
{6, 7}};
int mat_2[ROW_SIZE][COLUMN_SIZE] = {{3, 15},
{9, 14}};
int mat_result[ROW_SIZE][COLUMN_SIZE];
int mat_size = sizeof(mat_1) / sizeof(int);
int row_size = sizeof(mat_1) / sizeof(mat_1[0]);
int column_size = sizeof(mat_1[0]) / sizeof(int);
pthread_t threads[mat_size];
int thread_number = 0;
int thread_handler;
for (int row = 0; row < row_size; row++) {
for (int column = 0; column < column_size; column++) {
struct_sum *result;
result = static_cast<struct_sum *>(malloc(sizeof(struct_sum)));
result->value1 = mat_1[row][column];
result->value2 = mat_2[row][column];
result->result = 0;
thread_handler = pthread_create(&threads[thread_number], nullptr, routine, result);
if(thread_handler) return(-1);
std::cout << &(result->result)<<std::endl;
thread_number++;
mat_result[row][column] = result->result;
// free(result);
}
}
pthread_exit(nullptr);
}
I'm having two problems:
Even though the result has the same address in the main and in the thread, when I copy the value of i to ((struct_sum *)sum)->result, in the main function, result->result is still 0.
When I uncomment the memcpy() line the thread simply don't run, so I don't know how I'm doing it wrong.
I was expecting that in my main function the statement std::cout << (result->result) <<std::endl would return me the result of the operation, but the current value is 0.
So, how do I perform the memcpy() correctly in the thread?
You have to JOIN your threads. It means, wait them to finish.
The way you were doing is basically starting the thread and not giving it a guaranteed time do to anything. Besides that, some important change to the API, check the comments below:
void * routine(void * sum) {
int i = (((struct_sum *) sum)->value1 + ((struct_sum *) sum)->value2);
((struct_sum *)sum)->result = i;
// notice you don't need memcpy(), in fact...
// but you could use it here if you want... it won't fail.
// you have to use this function so it return your result to the main thread.
pthread_exit(sum);
}
int main(int argc, char * argv[]) {
int mat_1[ROW_SIZE][COLUMN_SIZE] = {{1, 2},
{6, 7}};
int mat_2[ROW_SIZE][COLUMN_SIZE] = {{3, 15},
{9, 14}};
int mat_result[ROW_SIZE][COLUMN_SIZE];
int mat_size = sizeof(mat_1) / sizeof(int);
int row_size = sizeof(mat_1) / sizeof(mat_1[0]);
int column_size = sizeof(mat_1[0]) / sizeof(int);
pthread_t threads[mat_size];
int thread_number = 0;
int thread_handler;
for (int row = 0; row < row_size; row++) {
for (int column = 0; column < column_size; column++) {
struct_sum *result;
result = static_cast<struct_sum *>(malloc(sizeof(struct_sum)));
result->value1 = mat_1[row][column];
result->value2 = mat_2[row][column];
result->result = 0;
thread_handler = pthread_create(&threads[thread_number], nullptr, routine, result);
if(thread_handler) return(-1);
// std::cout << &(result->result)<<std::endl;
thread_number++;
// forget this line below
// mat_result[row][column] = result->result;
}
}
// here you wait for the threads to JOIN
// here it means they actually "finished" their job
for (int i = 0; i < mat_size; i++)
{
struct_sum *result;
// here you wait for the threads to finish their job
// add something to your struct to "identify" the thread, so
// you can figure out where in the final matrix you put the result
pthread_join(threads[i], (void**)&result);
std::cout << result->result << "\n";
// this will print the correct sums: 4, 17, 15 and 21
// notice: it will be printed in ANY order, once you
// don't know which thread will finish first
// but result->result has the... result you need!
// you have to figure out how to fit this result in your matrix.
// but this is out of scope of the question
// and you can do yourself. have fun! :-)
// here you can free the result, you already got the value!
free(result);
}
// you don't need this line below... this goes to routine()
// pthread_exit(nullptr);
return 0;
}
I'm still relatively new to c++. I am trying to write a program that takes an array of numbers and reverses the order of those numbers in the array with a function. The program is as follows:
#include <iostream>
using namespace std;
void reverse(int *array, int size);
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / 4;
reverse(Array, size);
return 0;
}
void reverse(int *array, int size) {
int Array2[5];
for (int i = 0; i < size; i++) {
Array2[i + size] = array[i];
array[i + size] = Array2[i + size];
};
}
When I run this program, it crashes and I'm not sure why. If anyone can help my figure out why it would be much appreciated. Thank you.
Zenith has it, but there are a few points and quick hacks worth noting to help you out.
#include <iostream>
//using namespace std; don't need this, and using namespace std is overkill and often
// causes problems. It pulls in a lot of stuff that may conflict, case in point
// std::reverse now becomes reverse. Which reverse will you get? Your reverse or the standard
// library's reverse? Only pull in what you need, for example
using std::cout; // still not used, but makes a good example.
void reverse(int *array, int size)
{
// no need for the other array and another loop. You can swap each element for
//it's counterpart in the upper half of the array.
for (int i = 0; i < size /2 ; i++) // only need to go half way. Other half was
// already swapped doing the first half.
{
int temp = array[i]; // store a temporary copy of element i
array[i] = array[size-1-i]; // replace element i with it's counterpart
// from the second half of the array
array[size-1-i] = temp; // replace the counterpart of i with the copy of i
// or call std::swap(array[i], array[size-1-i]);
};
}
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
// int size = sizeof(Array) / 4; using 4 here can trip you up on a computer with
// a different sized int
int size = sizeof(Array) / sizeof(Array[0]);
// dividing the size of the array by the size of an element in the array will always
// get you the correct size
reverse(Array, size);
return 0;
}
Array2[i + size]
You're accessing out-of-bounds, no matter the value of i.
You probably meant Array2[size - 1 - i] to iterate the array backwards. (size - 1 is the index of the last element.)
by using swap you will get a much nicer solution which is also more efficient
void reverse(int *array, int size) {
for (int i = 0; i < size/2; i++) {
std::swap(array[i],array[size-1-i]);
};
}
When you say int size = sizeof(Array) / 4;, size is now (5 * sizeof(int)) / 4. That's how the sizeof operator works (at least when applied to arrays).
So size is probably 5, assuming a 4-byte int. Now, you get to reverse and its argument size is also 5.
You get to the for loop, and even at the first iteration, you have Array2[5] = /* something */ and array[5] = /* something */, both of which are buffer overruns.
Also, your reverse function doesn't actually do any reversing. Try this:
void reverse(int *arr, int size);
int main()
{
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / sizeof(int);
reverse(Array, size);
return 0;
}
void reverse(int *arr, int size)
{
int temp[5];
for (int i = 0; i < size; i++)
temp[size - 1 - i] = arr[i];
for (int i = 0; i < size; i++)
arr[i] = temp[i];
}
int initfunc(int *array, int len)
{
int i;
for(i=1; i <= len; i++)
{
array[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int *myarray = 0;
initfunc(myarray, 10);
}
I have run this code in C++ but showing me error. can you please tell me what is wrong with code.
Okay first of all you have to change the line
int *myarray = 0;
You have two options you can generate an array on the stack and on the heap. The stack example looks like this:
int myarray[10];
Where 10 is the size of you array.
Second your for loop is running out of bounds. You have to start with the index 0 and iterate up to array size -1. In our example 10-1=9
So you have to change the line
for(i=1; i <= len; i++)
to
for(i=0; i < len; i++)
the whole project should look like this:
int initfunc(int *array, int len)
{
int i;
for(i=0; i < len; i++)
{
array[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int myarray[10];
initfunc(myarray, 10);
}
I'm ignoring certain "best practices" in this example to be as close to your code as possible. One good intention would be to declare the length of that array just once and also bring that int i into the loop scope. Im leaving this here for you to try and exercise.
Why does the provided code crash at the following line?
data *fillA = (data*)calloc(matrixa->nzmax, sizeof(data));
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#include <time.h>
using namespace std;
struct csr
{
int rows;
int cols;
int nzmax;
int *rowPtr;
int *colInd;
double *values;
};
struct data
{
int entry;
int index;
};
bool descend(const data &a, const data &b)
{
return a.entry > b.entry;
}
static bool ascend(const data &a, const data &b)
{
return a.entry < b.entry;
}
void csrtranspose(struct csr *matrixa)
{
int i, j, counter;
double *tArray = NULL;
data *fillA = (data*)calloc(matrixa->nzmax, sizeof(data));//fails here
for (int i = 0; i < matrixa->nzmax; i++)
{
fillA[i].entry = matrixa->colInd[i];
fillA[i].index = i;
}
sort(fillA, fillA + matrixa->nzmax, ascend);
tArray = (double*)calloc(matrixa->nzmax, sizeof(double));
for (int i = 0; i < matrixa->nzmax; i++)
{
tArray[i] = matrixa->values[i];
}
for (int i = 0; i < matrixa->nzmax; i++)
{
matrixa->colInd[i] = fillA[i].entry;
matrixa->values[i] = tArray[fillA[i].index];
}
free(tArray);
free(fillA);
}
int main()
{
int i;
struct data *total = 0;
struct csr *s = 0;
int nrows = 6, ncols = 5, counter = 0, nzmax = 10, rows = 3, cols = 5;
double values[10] = {0.2135, 0.8648, 7, 0.3446, 0.1429, 6, 0.02311, 0.3599, 0.0866, 8 };
int rowPtr[4] = { 0, 3, 6, 10 };
int colInd[10] = { 0, 2, 4, 1, 2, 3, 0, 1, 2, 4 };
s = (struct csr*) calloc(1, sizeof(struct csr));
s->rows = rows;
s->cols = cols;
s->nzmax = nzmax;
s->rowPtr = (int*)calloc(s->rows + 1, sizeof(int));
s->colInd = (int*)calloc(s->nzmax, sizeof(int));
s->values = (double*)calloc(s->nzmax, sizeof(int));
for (i = 0; i<10; i++)
{
s->colInd[i] = colInd[i];
s->values[i] = values[i];
if (i <= s->rows)
{
s->rowPtr[i] = rowPtr[i];
}
}
csrtranspose(s);
getchar();
}
The reason why it crashes there is because memory has already been corrupted by previously faulty code. So, the problem is not there where it crashes, the problem is in code which executed earlier.
Specifically, this line:
s->values = (double*)calloc(s->nzmax, sizeof(int));
Allocates doubles, but uses sizeof(int), so it does not allocate enough memory.
EDIT
Recommendations:
As others have already pointed out, when working with C++, use the new operator instead of C-style memory allocation. It will save you from LOTS of problems.
If you insist on using C-style allocation, never use p = (type*)malloc( sizeof(type) ), always use p = (type*)malloc( sizeof( *p ) ). This will at least make it more evident when you make the very common mistake of allocating memory for the wrong type.
The line (double*)calloc(s->nzmax, sizeof(int)); in itself is a good reason to switch to C++ allocation, where it's impossible to make that mistake even if you copy-and-paste.
You're allocating too little memory and writing out of bounds.
Since all your sizes are known at compile time, you don't really need dynamic allocation at all.
I just started using OpenGL. This is my first code:
// OpenGL hello program
#include<iostream>
#include <GL/glut.h>
#include <cstring>
void display() {
glClear(GL_COLOR_BUFFER_BIT);
char message[] = "Hello, world!";
glRasterPos2d(0, 0);
for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, message[i]);
}
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutCreateWindow("OpenGL hello program");
glutDisplayFunc(display);
glutMainLoop();
}
The error I am getting is: Warning: comparison between signed and unsigned integer expressions (line 9).
I also tried writing a new code then to see whats causing the problem:
#include<iostream>
#include <cstring>
void display1() {
char message[] = "Hello, world!";
for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
std::cout<<message[i];
}
int main() {
display1();
}
This code works perfectly fine. Why is the first code not working fine?
EDIT:
Following up on Cyber's annswer, I changed the loop to:
for (unsigned int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
But the OpenGL code does not do the expected i.e. show "Hello, world!" message in the window. It just creates a window with "OpenGL hello program" written at the top and nothing else.
This line is the problem
for (int i = 0; i < sizeof(message) / sizeof(message[0]); i++)
The operator sizeof has the return type of std::size_t which is therefore what you should use for the type of your variable i. std::size_t is an unsigned type, so the compiler is warning you that you are comparing a signed type (int) to an unsigned type, because the comparison is potentially unsafe if the value of one variable is not in the representable range of in the other type.
for (std::size_t i = 0; i < sizeof(message) / sizeof(message[0]); ++i)
Or simply use a range-based for loop.
for (auto i : message)
{
std::cout << i; // i is a char from the message array
}
for (int i =0,i<sizeof ....)
That line is the problem. The sizeof function returns an unsigned integer thus causing error when compared to the signed int.
Try creating an int variable for the sizeof like this:
int size=sizeof()...
Then replace in your line as follows:
for (int i=0,i<size...)