I am quite new to programming with C, so hope someone can bear with me and help me solve the issue I am facing.
I am writing a code to estimate the value of pi with Monte-Carlo method. however, when I build and debug I get an error that says:
"Exception thrown: write access violation.
a was 0x1110112.
I get this error in generate_random_array function
in this line of code:
a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;
I am posting the whole code as well for reference.
note: I am using visual studio with MSVC compiler
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random_array(int sz, double a[]);
void count_points_inside_circle(int sz, double x[], double y[], int* counter);
int main()
{
int tot = 1000000000;
int incircle_c = 0;
double distance_sq, pi;
double* x = NULL;
double* y = NULL;
/*create arrays in the heap*/
x = malloc(tot * sizeof(double));
y = malloc(tot * sizeof(double));
/*generate random locations*/
generate_random_array(tot, x);
generate_random_array(tot, y);
/*count the points inside te circle by checking the location distance*/
count_points_inside_circle(tot, x, y, &incircle_c);
/*estimate pi*/
pi = 4.0 * incircle_c / (double)tot;
printf("pi estimated value using %d samples was found to be %lf", tot, pi);
free(x);
free(y);
return 0;
}
void generate_random_array(int sz, double a[]) {
int i;
srand(time(NULL));
for (i = 0; i < sz; i++)
a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;
}
void count_points_inside_circle(int sz, double x[], double y[],int* counter_p) {
int i;
double distance_sq;
for (i = 0; i < sz; i++) {
distance_sq = x[i] * x[i] + y[i] * y[i];
if (distance_sq <= 1)
(*counter_p)++;
}
}
You must always check the pointer returned from malloc against NULL. For example:
x = malloc(n * sizeof *x);
if (x == NULL) { /* Handle the failure and/or exit */ }
On the other hand, this task doesn't require use of an array (or allocated space used as an array) at all; you need only the number of points inside the circle and the number of total points generated. It could be simply done like that:
#include <stdio.h>
#include <stdlib.h>
double estimate_pi (unsigned trial_count)
{
const double rr = (double)RAND_MAX * RAND_MAX;
unsigned inner_point_count = 0;
unsigned i;
for (i = 0; i < trial_count; ++i) {
double x = rand();
double y = rand();
if (x * x + y * y <= rr)
++inner_point_count;
}
return 4.0 * inner_point_count / trial_count;
}
int main (void)
{
printf("%f\n", estimate_pi(1000000000));
return 0;
}
Note that, quality of random number generator used by the standard library significantly affects the result of this simulation.
I have a code where It wants to read which operation it wants to do and then calculate the numbers using the operation. I have the library code and header but the main code, I don't know what to implement within the body. I have a skeleton code however I'm drawing a blank on what else I need to do.
If this helps, the operation I'm trying to achieve is:
./statistics mean 10 20 30
and the answer should be: 20.0
Library Header:
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H
float OP_MEAN(int size, float * values);
float OP_MAX(int size, float * values);
float OP_SD(int size, float * values);
#endif
Library Code:
float OP_MEAN(int size, float * values)
{
int i;
float sum = 0.0;
for(i = 0; i < size; i++)
{
sum += values[i];
}
return sum/n;
}
float OP_MAX(int size, float * values)
{
int i;
float maximum = 0.0;
for(i = 0; i < size; i++)
{
if (values[i] > maximum)
{
maximum = values[i];
}
}
return maximum;
}
float OP_SD(int size, float * values)
{
float mean = OP_MEAN(size, values);
float sum = 0.0, un_sqrt_sd = 0.0;
int i;
for(i = 0; i < size; i++)
{
sum += pow(double(values[i] - mean), double(2));
}
un_sqrt_sd = (float) sum / (size - 1);
return (float) sqrt(double(un_sqrt_sd));
}
Main Code:
#include <stdio.h>
#include "my_lib.h"
// define the operations as enum here
enum operations{
OP_MEAN
OP_MAX
OP_SD
};
int main(int argc, char ** argv){
//parse command line arguments
enum operations op;
// 1. find the operator
if (strcmp(argv[1], "max") ...){ // check with man strcmp
op = OP_MAX;
}...
// 2. define an array with the necessary size
// 3. load numbers using my_atoi()
float (*fp)(int size, float * values); // declared function pointer variable
// use a switch to set the function pointer
switch(op_var){
case(OP_MAX):
fp = ... // set the function pointer
}
// invoke the function pointer
float result = fp(size, array)
printf("%.1f\n", result);
return 0;
}
I'm getting a seg fault within this code, but I can't find the problem anywhere. It compiles just fine with -lpthread, but it just won't run. This program takes in an integer from the command line and then creates a new thread to calculate the collatz conjecture using that value. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void print_con();
void calc_con(int *n);
int * values[1000];
int main(int argc, char * argv[])
{
int* num;
*num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);
pthread_join(thread, NULL);
print_con();
return 0;
}
void calc_con(int *n)
{
int i = 0;
int * x;
*x = *n;
*values[0] = *x;
while(*x > 1)
{
if(*x % 2 == 0)
*x /= 2;
else if(*x % 2 == 1)
{
*x *= 3;
*x++;
}
i++;
*values[i] = *x;
}
pthread_exit(0);
}
void print_con()
{
int i;
for(i = 0; i < 1000; i++)
{
if(*values[i] > 0)
printf("%d", *values[i]);
}
}
okay you need to pass a void * as an argument to pthread_create, but you still need to respect the basics:
int* num;
*num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);
Here *num = 15; you're writing 15 to an uninitialized pointer. That's undefined behaviour.
I would do:
int num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, &calc_con, &num);
note that you don't have to cast to void * from pointers on non-void. Since num is declared in the main routine, you can pass a pointer on it to your threads safely.
note that as pointed by dasblinkenlight, you also have to fix the recieving end, in calc_con, which has the same issue:
int * x; // uninitialized pointer
*x = *n; // copy data "in the woods"
just dereference into a local variable and you have your value:
int x = *((int *)n);
and another one:
int * values[1000];
is an uninitialized array of integer pointers, not an array of integers like you're intending. It should be
int values[1000];
then
values[0] = x;
(it's not because there's a lot of * operators that it's good code)
You are passing an int to your thread using a void*. This will work on many platforms, but there is no guarantees that the number would "round-trip" correctly. Once you get pointer back, you save it in a dereferenced uninitialized pointer, which is incorrect.
Pass a pointer to num instead, and copy the pointer into x directly:
void calc_con(void *n);
...
void calc_con(void *n) {
int i = 0;
int * x = n;
*values[0] = *x;
while(*x > 1) {
if(*x % 2 == 0) {
*x /= 2;
} else if(*x % 2 == 1) {
*x *= 3;
*x++;
}
i++;
*values[i] = *x;
}
pthread_exit(0);
}
...
int num = 15;
pthread_create(&thread,(pthread_attr_t*)NULL, calc_con, (void *)&num);
I have the following code shown below
To call the function the code looks similar to the following:
#define N 2
static float m1[N][N] = {{1.0, -0.02}, {0.0, 1.0}};
static float m2[N][1] = {{1.5f}, {1.5f}};
static float result[N][1];
int main(void)
{
matrix_multiply((float*) m1, (float*) m2, N, N, 1, (float*) result);
}
void matrix_multiply(float* input_matrix1, float* input_matrix2, int m, int p, int n, float* output_matrix)
{
// Matrix Multiplication Routine
// input_matrix1= input matrix (m x p)
// input_matrix2 = input matrix (p x n)
// m = number of rows in input_matrix1
// p = number of columns in input_matrix1 which should equal the number of rows in input_matrix2
// n = number of columns in input_matrix2
// output_matrix = output matrix = input_matrix1*input_matrix2 (m x n)
//.....Code that does matrix multiplication
}
I haven't come across the (float*) being used when calling a function. Can someone describe it in detail.
The notation (float *)X is a cast. The cast is necessary if the matrix multiply function is declared (or defined) before it is used, as it should be, because the types being passed to the function are not float * as the function expects but float (*)[2] (which is a pointer to an array). The casts tell the compiler 'we know more about this C than you do', even though that is a very debatable proposition.
Here is a mildly modified version of the code in the question:
#define N 2
static float m1[N][N] = {{1.0, -0.02}, {0.0, 1.0}};
static float m2[N][1] = {{1.5f}, {1.5f}};
static float result[1][N];
void matrix_multiply(float *input_matrix1, float *input_matrix2, int m, int p, int n, float *output_matrix);
int main(void)
{
matrix_multiply( m1, m2, N, N, 1, result);
matrix_multiply(&m1[0][0], &m2[0][0], N, N, 1, &result[0][0]);
matrix_multiply((float*) m1, (float*) m2, N, N, 1, (float*) result);
}
void matrix_multiply(float *input_matrix1, float *input_matrix2, int m, int p, int n, float *output_matrix)
{
// Matrix Multiplication Routine
// input_matrix1 = input matrix (m x p)
// input_matrix2 = input matrix (p x n)
// m = number of rows in input_matrix1
// p = number of columns in input_matrix1 and the number of rows in input_matrix2
// n = number of columns in input_matrix2
// output_matrix = output matrix = input_matrix1*input_matrix2 (m x n)
//.....Code that does matrix multiplication
}
When compiled with GCC 4.7.1 on Mac OS X 10.8.4, the output is:
$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -c matmul89.c
matmul89.c: In function ‘main’:
matmul89.c:10:5: warning: passing argument 1 of ‘matrix_multiply’ from incompatible pointer type [enabled by default]
matmul89.c:6:6: note: expected ‘float *’ but argument is of type ‘float (*)[2]’
matmul89.c:10:5: warning: passing argument 2 of ‘matrix_multiply’ from incompatible pointer type [enabled by default]
matmul89.c:6:6: note: expected ‘float *’ but argument is of type ‘float (*)[1]’
matmul89.c:10:5: warning: passing argument 6 of ‘matrix_multiply’ from incompatible pointer type [enabled by default]
matmul89.c:6:6: note: expected ‘float *’ but argument is of type ‘float (*)[2]’
matmul89.c: In function ‘matrix_multiply’:
matmul89.c:17:29: warning: unused parameter ‘input_matrix1’ [-Wunused-parameter]
matmul89.c:17:51: warning: unused parameter ‘input_matrix2’ [-Wunused-parameter]
matmul89.c:17:70: warning: unused parameter ‘m’ [-Wunused-parameter]
matmul89.c:17:77: warning: unused parameter ‘p’ [-Wunused-parameter]
matmul89.c:17:84: warning: unused parameter ‘n’ [-Wunused-parameter]
matmul89.c:17:94: warning: unused parameter ‘output_matrix’ [-Wunused-parameter]
$
The unused parameter warnings are reasonable; the function is still a dummy with no code. Line 10 is the call to matrix_multiply() without the casts. As you can see, GCC diagnoses that the types of the matrix arguments are not float * but are pointers arrays. The second call is the way I'd write it, avoiding any need for casts. The third call bludgeons the compiler into accepting the code with the casts, and it will in fact work correctly, but there is really no need to do the bludgeoning.
Working C99 code
If you've got C99 available, you can make use of VLAs — variable length arrays — to write the code neatly:
#include <stdio.h>
#define N 2
static float m1[N][N] = {{1.0, -0.02}, {0.0, 1.0}};
static float m2[N][1] = {{1.5f}, {1.5f}};
static float result[1][N];
void matrix_multiply(int m, int p, int n, float matrix1[m][p], float matrix2[p][n], float output[m][n]);
void matrix_print(const char *tag, int m, int n, float matrix[m][n]);
int main(void)
{
matrix_multiply(N, N, 1, m1, m2, result);
matrix_print("m1", N, N, m1);
matrix_print("m2", N, 1, m2);
matrix_print("m3", 1, N, result);
}
void matrix_multiply(int m, int p, int n, float matrix1[m][p], float matrix2[p][n], float output[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
output[i][j] = 0.0;
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
for (int k = 0; k < n; k++)
output[i][k] += matrix1[i][j] * matrix2[j][k];
}
void matrix_print(const char *tag, int m, int n, float matrix[m][n])
{
printf("%s (%d x %d):\n", tag, m, n);
for (int i = 0; i < m; i++)
{
char *pad = "[";
for (int j = 0; j < n; j++)
{
printf("%s%6.3f", pad, matrix[i][j]);
pad = ", ";
}
printf("%s", " ]\n");
}
}
This compiles without warnings and produces the plausible-looking output:
m1 (2 x 2):
[ 1.000, -0.020 ]
[ 0.000, 1.000 ]
m2 (2 x 1):
[ 1.500 ]
[ 1.500 ]
m3 (1 x 2):
[ 1.470, 1.500 ]
Writing the code to simulate the address arithmetic using C89 is fiddly — far from impossible, but fiddly.
Working C89 code
#include <stdio.h>
#define N 2
static float m1[N][N] = {{1.0, -0.02}, {0.0, 1.0}};
static float m2[N][1] = {{1.5f}, {1.5f}};
static float result[1][N];
void matrix_multiply(float *matrix1, float *matrix2, int m, int p, int n, float *output);
void matrix_print(const char *tag, int m, int n, float *matrix);
int main(void)
{
matrix_multiply(&m1[0][0], &m2[0][0], N, N, 1, &result[0][0]);
matrix_print("m1", N, N, &m1[0][0]);
matrix_print("m2", N, 1, &m2[0][0]);
matrix_print("m3", 1, N, &result[0][0]);
return 0;
}
/*
** Matrix Multiplication Routine
** matrix1 = input matrix (m x p)
** matrix2 = input matrix (p x n)
** m = number of rows in matrix1
** p = number of columns in matrix1 and number of rows in matrix2
** n = number of columns in matrix2
** output = output matrix = matrix1 * matrix2 (m x n)
*/
void matrix_multiply(float *matrix1, float *matrix2, int m, int p, int n, float *output)
{
int i, j, k;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
output[i*n+j] = 0.0;
for (i = 0; i < m; i++)
for (j = 0; j < p; j++)
for (k = 0; k < n; k++)
output[i*n+k] += matrix1[i*p+j] * matrix2[j*n+k];
}
void matrix_print(const char *tag, int m, int n, float *matrix)
{
int i, j;
printf("%s (%d x %d):\n", tag, m, n);
for (i = 0; i < m; i++)
{
char *pad = "[";
for (j = 0; j < n; j++)
{
printf("%s%6.3f", pad, matrix[i*n+j]);
pad = ", ";
}
printf("%s", " ]\n");
}
}
The output for the C89 and C99 code is the same.
I have the following warnings during the compilation:
solver.c:24: warning: passing argument 2 of ‘mtrx_multiple’ from incompatible pointer type
mat.h:5: note: expected ‘double *’ but argument is of type ‘double **’
solver.c:30: warning: assignment makes pointer from integer without a cast
solver.c:39: warning: assignment makes pointer from integer without a cast
/tmp/ccmU9zRf.o: In function `vec_norm':
math.c:(.text+0x331): undefined reference to `sqrt'
collect2: ld returned 1 exit status
the lines are:
solver.c
double *cg_solve( sparse_mat_t A, double *b, double *x ) {
double *a;
double **r;
double *be;
double **p;
double **x0;
x0[0] = vec_copy(x, size);
...
line 24: r[0] = vec_subtraction( b, mtrx_multiple(A, x0), size );
line 30: x0[k+1] = vec_addition( x0[k], vec_numb_multiple(a[k], p[k], size), size );
line 39: p[k+1] = vec_addition( r[k+1], vec_numb_multiple(be[k], p[k], size), size );
}
math.h
line 5: double *mtrx_multiple (sparse_mat_t A, double *c);
The function that are used there: (math.c)
double *vec_subtraction (double *a, double *b, int n) {
double *result = malloc(sizeof(double)*n);
int i;
for(i=0; i<n; i++)
result[i] = a[i]-b[i];
return result;
}
double *vec_addition (double *a, double *b, int n) {
double *result = malloc(sizeof(double)*n);
int i;
for(i=0; i<n; i++)
result[i] = a[i]+b[i];
return result;
}
double *vec_numb_multiple (double a, double *b, int n) {
double *result = malloc(sizeof(double)*n);
int i;
for(i=0; i<n; i++)
result[i] = a*b[i];
return result;
}
double *mtrx_multiple (sparse_mat_t A, double *c) {
double *result;
int i, j;
result = malloc((A.size) * sizeof *result);
printf("c.n: %d \n", A.size);
for (i = 0; i < A.size; i++) {
int v = 0;
for (j = A.ia[i]; j < A.ia[i + 1]; j++) {
v += A.a[j] * c[A.ja[j]];
}
result[i] = v;
}
return result;
}
double vec_norm (double *a, int n){
double result;
int i;
for(i=0; i<n; i++)
result = result + ( a[i] * a[i] );
result = sqrt(result);
return result;
}
double *vec_copy (double *a, int n) {
double *result;
int i;
for(i=0; i<n; i++)
result[i] = a[i];
return result;
}
I will be grateful for any help.
EDIT
I found the solution to the x0 problem, thanks Ben. Now what left is:
solver.c:30: warning: assignment makes pointer from integer without a cast
solver.c:39: warning: assignment makes pointer from integer without a cast
/tmp/ccL4uSoH.o: In function 'vec_norm':
math.c:(.text+0x331): undefined reference to 'sqrt'
collect2: ld returned 1 exit status
Based on what you've posted, I'm going to guess that you don't have a declaration for vec_numb_multiple in scope before you call it, and the compiler is implicitly typing it to return int; that would lead to the warnings on lines 30 and 39.
The undefined reference to sqrt() means you aren't linking in the standard math library; I'm assuming you're using gcc, so you would need to add -lm to the command line.
It's a really bad idea to use a standard library file name for your own code (math.h, math.c).
replace (line 24)
r[0] = vec_subtraction( b, mtrx_multiple(A, x0), size );
with
r[0] = vec_subtraction( b, mtrx_multiple(A, x0[0]), size );
You said you whant to multiply a matrix (A I guess) with a vector, so the second argument must be a vector. x0 is a pointer to pointers which can be see as a 2D array of doubles, it means a single cell of x0 is an array of doubles (ie. what you could call a vector). This is why you want to pass x0[0], not just x0 which is : many arrays.
see John's aswer for the rest.