This is the programm I wrote:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
void meanVariance(double* x, int n, double* mean, double* variance);
double* scanVector(int length);
void meanVariance(double* x, int n, double* mean, double* variance){
double sum = 0;
for (int i = 0; i < n; i++){
sum += x[i];
}
*mean = sum / ((double)n);
sum = 0;
for (int i = 0; i < n; i++)
{
double sq = x[i] - *mean;
sum += sq * sq;
}
if (n != 1)
{
*variance = sum / ((double)n );
}
else
{
*variance = 1;
}
}
int main() {
double *x = malloc(sizeof(double)), mean = 0, variance = 0;
int n = 0;
do {
n++;
x = realloc(x, sizeof(double) * (n));
printf("Type in the %d- Number
: ", n);
scanf("%lf", (x+(n-1)));
meanVariance(x, n, &mean, &variance);
printf("Mittelwert: %f\n", mean);
printf("Varianz: %f\n", variance);
} while(*(x+(n-1)) != 0);
free(x);
}
I don't unterstand why there is no & in the scanf function. The program works but I just don't unterstand why cause the & is missing. I'm guessing it has something to do with the pointer x however i'm not sure at all.
You only need & if you need to take the address of a value, that is, produce a pointer to that value. But x is already a pointer, so there is no need for &. It would be quite wrong to use & in this case, because you'd end up with a pointer to a pointer!
There is also some pointer arithmetic going on: x+(n-1) advances the pointer by n-1 positions in memory, each position being sizeof(double) bytes. If you view x as an array, it's the same as &x[n-1]; that is, the address of the n-1th element in the array.
x+(n-1) - this is pointer arithmetic (study the term).
The [] operator is specified with the guarantee that array[i] (readable) is 100% equivalent to *((array) + (i)) (unreadable).
In your case &x[n-1] is the same as &*( (x) + (n-1) ). The & and * cancel each other out and what remains is x + (n-1).
So we can unslopify the code using readable form like this: scanf("%lf", &x[n-1]);
I program in C and I am testing my program and I don't understand why I get the error -1073741819 (0xC0000005). Here is the Code:
#include <stdio.h>
#include <stdlib.h>
double interpol(double x0, double y0, double x1, double y1, double h) {
double ergebnis = (y1 - y0) / (x1 - x0) * h;
printf("%.2f\n", ergebnis);
return ergebnis;
}
void interpol_array(double *x_org, double *y_org, int dim_org,
double *x_int, double *y_int, int dim_int,
int n) {
int j, i;
double h;
i = 0;
y_org[0] = y_int[0];
for (j = 1; j < dim_int; j++) {
if (j % (n + 1) == 0 && j != 0) {
i++;
x_int[j] = x_org[i];
y_int[j] = x_org[i];
continue;
}
printf("%.2f ", y_org[0]);
}
}
int main() {
/* Pointer erzeugen auf null setzen */
double *xArrayOriginal = NULL;
double *yArrayOriginal = NULL;
double *xArrayInterpol = NULL;
double *yArrayInterpol = NULL;
/**/
int dimOriginal = 2;
int n = 3;
int dimInterpol = (n + 1) * (dimOriginal + 1) - n; /*+1 wegen der null*/
int i, j;
double h;
/* Array für die Originalwerte erzeugen */
xArrayOriginal = (double *)malloc(dimOriginal * sizeof(double));
yArrayOriginal = (double *)malloc(dimOriginal * sizeof(double));
/*Array für das Interpolierte Array erzeugen*/
xArrayInterpol = (double *)malloc(dimInterpol * sizeof(double));
yArrayInterpol = (double *)malloc(dimInterpol * sizeof(double));
xArrayOriginal[0] = 0;
xArrayOriginal[1] = 1;
xArrayOriginal[2] = 2;
yArrayOriginal[0] = 2;
yArrayOriginal[1] = 4;
yArrayOriginal[2] = 8;
interpol_array(xArrayOriginal, yArrayOriginal, dimOriginal, xArrayInterpol,
yArrayInterpol, dimInterpol, n);
return 0;
}
In my program I have 4 dynamic arrays. 2 dynamic arrays for origin x and y values and 2 dynamic arrays for interpolated x and y values. I don't program the full interpolation because I got an error. Therefore I searched the error and found out that when I use
printf("%.2f ", y_org[0]);
I get the error that you can see above. Only when I change it to
printf("test");
it works fine. So why do I get this error. what is wrong with my array list?
In the function main, the lines
int dimOriginal = 2;
...
xArrayOriginal =(double *)malloc(dimOriginal*sizeof(double));
yArrayOriginal =(double *)malloc(dimOriginal*sizeof(double));
allocate arrays for 2 double elements each. However, the lines
xArrayOriginal[2] =2;
...
yArrayOriginal[2] =8;
write out of bounds of these arrays, as the only valid elements numbers are 0 and 1. This causes undefined behavior.
Also, in the function interpol_array, the following line causes undefined behavior:
y_org[0] = y_int[0];
This is because y_int has been assigned the value of yArrayInterpol in main, but the contents of yArrayInterpol has not been initialized.
I'm working on some code that initialises a couple of blocks of memory with random values. I will use these blocks of memory as matrices for the weights and biases in a neural net later on but that is not the point of this question.
I have two pieces off code (Code A & Code B) which does essentially the same thing, namely initialising a block of memory with random values. Both pieces of code compile just fine, however when I execute Code B I get a segmentation fault 11 error and the code stops executing. Code B works with a structure of variable member length and I believe this creates the problem. However i don't know how to fix this.
My question: Does someone know what the problem causes and how to fix it? I would really love to have Code B working since this is convenient in the code later on. I have pasted both pieces of code below. The system where I have this code tested is macOS.
Any help would be greatly appreciated!
Code A:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define DEBUG
/*
Function prototypes
*/
void init_rand(float *p, int size);
int main(int argc, char const *argv[])
{
int neurons [] = {10,10,10}; // use this array to define the neuralnet
int layers = sizeof(neurons)/sizeof(int); // this calculates the amount of layers in the neuralnet (i.e. the amount of members in the array 'neurons')
// array of pointers for the memory given by malloc
float *pwl[layers];
float *pbl[layers];
float *pzl[layers];
float *pal[layers];
for (int i = 1; i < layers; i++) // create memory for the matrices and assign the start adress of each matrix to the pointers
{
pwl[i] = (float *)malloc(neurons[i]*neurons[(i-1)]*sizeof(float));
pbl[i] = (float *)malloc(neurons[i]*sizeof(float));
pzl[i] = (float *)malloc(neurons[i]*sizeof(float));
pal[i] = (float *)malloc(neurons[i]*sizeof(float));
}
for (int i = 1; i < layers; i++) // initialize the weights and the biases with random values
{
init_rand(pwl[i], neurons[i]*neurons[i-1]);
init_rand(pbl[i], neurons[i]);
}
return 0;
}
/*
Random generator with a gaussian distribution. Mean = 0, Variance = 1
*/
double gaussrand()
{
static double V1, V2, S;
static int phase = 0;
double X;
if(phase == 0)
{
do
{
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
} else
X = V2 * sqrt(-2 * log(S) / S);
phase = 1 - phase;
return X;
}
/*
This function initializes a float array with random gaussian distributed numbers
*/
void init_rand(float *p, int size)
{
for (int i = 0; i < size; i++, p++)
{
*p = (float)gaussrand();
#ifdef DEBUG
printf("%d:*p = %f\n", i, *p); //
#endif
}
}
Code B:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define DEBUG
struct neuralnet
{
int struct_size;
float *pwl[0];
float *pbl[0];
float *pzl[0];
float *pal[0];
};
/*
Function prototypes
*/
void init_rand(float *p, int size);
struct neuralnet* create_neuralnet(struct neuralnet* pnet, int layers);
int main(int argc, char const *argv[])
{
int neurons [] = {10,10,10}; // use this array to define the neuralnet
int layers = sizeof(neurons)/sizeof(int); // this calculates the amount of layers in the neuralnet
struct neuralnet *pnet; // create a struct neuralnet pointer
pnet = create_neuralnet(pnet, layers); // this function will create a neuralnet structure with variable size members
for (int i = 1; i < layers; i++) // create memory for the matrices and assign the start adress of each matrix to the pointers
{
pnet->pwl[i] = (float *)malloc(neurons[i]*neurons[(i-1)]*sizeof(float));
pnet->pbl[i] = (float *)malloc(neurons[i]*sizeof(float));
pnet->pzl[i] = (float *)malloc(neurons[i]*sizeof(float));
pnet->pal[i] = (float *)malloc(neurons[i]*sizeof(float));
}
for (int i = 1; i < layers; i++) // initialize the weights and the biases with random values
{
init_rand(pnet->pwl[i], neurons[i]*neurons[i-1]);
init_rand(pnet->pbl[i], neurons[i]);
}
return 0;
}
/*
Random generator with a gaussian distribution. Mean = 0, Variance = 1
*/
double gaussrand()
{
static double V1, V2, S;
static int phase = 0;
double X;
if(phase == 0)
{
do
{
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
} else
X = V2 * sqrt(-2 * log(S) / S);
phase = 1 - phase;
return X;
}
/*
This function initializes a float array with random gaussian distributed numbers
*/
void init_rand(float *p, int size)
{
for (int i = 0; i < size; i++, p++)
{
*p = (float)gaussrand();
#ifdef DEBUG
printf("%d:*p = %f\n", i, *p); //
#endif
}
}
/*
This function creates the structure with members of variable length
*/
struct neuralnet* create_neuralnet(struct neuralnet *pnet, int layers)
{
pnet = (struct neuralnet *)malloc(sizeof(*pnet) + sizeof(float *) * layers * 4);
return pnet;
}
I'm trying to get monochrome image from .bmp image with using bitmap_image.hpp library. But in one place (Pic[i][j] = 0.3 * r + 0.59 * g + 0.11 * b;) i receive that error: Unhandled exception at 0x0019BD8F in PicCircle.exe: 0xC0000005: Access violation writing location 0x011CF000. . So, that's wrong with it?
code:
#define _SCL_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "bitmap_image.hpp"
#define C 0.01
double** ArrayCreate ( int M, int N )
{
int i;
double** ArrayRoot;
ArrayRoot = (double **)malloc(sizeof(double*) * M);
for (i = 0; i < M; i++)
ArrayRoot[i] = (double *)malloc(sizeof(double) * N);
return ArrayRoot;
}
void ArrayDestroy ( double** Array , int M)
{
int i;
for (i = 0; i < M; i++){
Array[i] = (double *)realloc(Array[i], 0);
};
Array = (double **)realloc(Array, 0);
}
void main ( void )
{
double** Pic;
unsigned char r, g, b;
int H, W, i, j;
bitmap_image image("m1.bmp");
H = image.height();
W = image.width();
Pic = ArrayCreate(H, W);
for (i = 0; i < W; i++)
for (j = 0; j < H; j++)
{
image.get_pixel(i, j, r, g, b);
Pic[i][j] = 0.3 * r + 0.59 * g + 0.11 * b;
}
for (i = 0; i < W; i++)
for (j = 0; j < H; j++)
{
if (abs(sqrt(pow(Pic[i + 1][j] - Pic[i][j], 2) + pow(Pic[i][j + 1] - Pic[i][j], 2))) >= C)
Pic[i][j] = 1;
else
Pic[i][j] = 0;
}
ArrayDestroy(Pic, H);
}
In your first loop you access the Pic array as Pic[width][height], but in the second loop you access it as Pic[height][width].
One of those two is incorrect, probably the first one.
Fixing your for loop should correct the issue.
This:
ArrayRoot = (double **)malloc(sizeof(int*) * M);
looks super-broken; it assumes sizeof (int *) to be the same as (sizeof double *) which is probably true, but still a very broken thing to write.
The follow-up is worse:
ArrayRoot[i] = (double *)malloc(sizeof(int) * N);
since sizeof (int) is very probably smaller than sizeof (double) this is going to lead to horror.
The way to avoid this category of error is to never write the type name in the malloc() argument: dereference the pointer being assigned to, instead. The latter would then become:
ArrayRoot[i] = malloc(N * sizeof *ArrayRoot[i]);
^^^^^^^^^^^^^
this part is to
the left of the =
This also drops the cast of course.
I keep getting the following error message when I run my code in debug.
Windows has triggered a breakpoint in Linear Equations 331.exe.
This may be due to a corruption of the heap, which indicates a bug in
Linear Equations 331.exe or any of the DLLs it has loaded.
Then it comes up with a break/continue.
The code uses a Gauss-Siedel Iterative method to solve a n x n system of linear equations. In this case I need to find the total amount of stretch (X) for 3 bungee cords in series,with 3 people (A,B,C) attached to it. Each solution has a different permutation of the people attached (i.e. A,B,C ; A,C,B ; B,A,C etc.)
We were supplied with a memory allocation header file called alloc.h, though I don't fully understand how it works which may be causing my problem. It worked fine before I started using ALLOCATE() for more variables. Any help in explaining why this is happening would be really helpful.
The main code is first. Header Files are at the bottom. Sorry if the code is a bit messy. I tried to comment as best as I could:
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "allocate.h"
#include "iter.h"
void position_solve(int n,int k,double X[], double x[],double order[]);
void inverse(int n, double A[],double X[],double b[]);
void swap(double *,double*);
void permute(int n, double a[]);
int noofpermutations();
void next(int n,double a[]);
void permutation(int n, double a[]);
int count = 0;
int main(void)
{
int i,j,k,num=0, n=3, p=noofpermutations(n);
double *A = NULL, *m = NULL, *X = NULL,* b= NULL,*K=NULL, *x=NULL, *order=NULL, *length=NULL;
/* Allocate the required memory */
ALLOCATE(A, double, n * n);
ALLOCATE(m, double, n * p);
ALLOCATE(b, double, n);
ALLOCATE(x, double, n * p);
ALLOCATE(K, double, n * p);
ALLOCATE(X, double, n);
ALLOCATE(order,double, n);
ALLOCATE(length,double,1);
/*Defining the Order of A,B,C jumpers where 1 = A, 2 = B, 3 = C*/
printf("+-----------------------------------------------------------------------------+\n");
printf("The Order of Bungee Jumpers A,B and C is represented by \n1,2,and 3 respectively. \n");
printf("\n+-----------------------------------------------------------------------------+\n");
for(i=0;i<n;i++){
order[i] = i+1;
b[i] = 0;
}
length[0] = 0;
/*Hardcoding k(spring constant),x(initial length of each bungee cord) and m(mass in kg) for 3 bunjee jumpers*/
K[0] = 50;
K[1] = 100;
K[2] = 50;
m[0] = -60*9.81;
m[1] = -70*9.81;
m[2] = -80*9.81;
x[0] = 20;
x[1] = 20;
x[2] = 20;
for(i=3;i<n*p;i++){
K[i] = 0;
m[i] = 0;
x[i] = 0;
}
/*Generate Permutations of K,m for the given Order of Bungee Jumpers */
permutation(n,K);
permutation(n,m);
permutation(n,order);
/*Calculate A matrix*/
for(k=0;k<p;k++){
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if(i==j){
A[i*n + j] = -K[k*n + i] - K[k*n + j];
}
else if(j == (i+1)){
A[i*n+j] = K[k*n + j];
A[j*n+i] = K[k*n + j];
}
else if(j>(i+1)){
A[i*n + j] = 0;
}
}
}
printf("\nFor a Bungee Jumper order %1.0lf %1.0lf %1.0lf :\n",order[k*n],order[k*n+1],order[k*n+2]);
/*Determine multiple X (stretch of bungee in m) vecotrs*/
/*Extract a single RHS vector (from B) into b*/
for(i=0;i<n;i++){
b[i]= m[k*n + i];
}
/*Perform Iterative Method*/
iter_solve(n, A, b, X);
/* Output X solutions*/
printf("\nX = [\n");
for (j = 0; j < n; j++) {
printf("%f ", X[j]);
printf("\n");
}
printf("]\n");
/*Determine Order of Jumpers*/
position_solve(n,k,X,x,order);
printf("--------------------------------------------\n\n");
/*If A,B,C Permutation find inverse*/
if(((int)(order[k*n])==1) && ((int)(order[k*n+1])==2)){
inverse(n,A,X,b);
}
}
/* Free allocated memory */
FREE(A);
FREE(b);
FREE(x);
FREE(X);
FREE(order);
FREE(length);
FREE(m);
return 0;
}
void iter_solve(int n, double A[], double b[], double x[])
{
int i, j, k = 0;
double sum, delta = 0.2, x_store;
/*Check for division by zero and guess X=Zeros*/
for(i=0;i<n;i++){
x[i] = 0;
if(fabs(A[i*n + i]) < ZERO){
//exit if division by zero occurs
printf("Division by zero occurs. Preconditioning A matrix may be required.");
exit(EXIT_FAILURE);
}
}
/*Perform Gauss-Seidel Iteration*/
while( (delta>TOL) && (k<MAX_ITER) ){
for(i = 0; i < n; i++){
x_store = x[i];
sum = 0;
/*Sum for j<i*/
for(j = 0;(j < i); j++){
sum += A[i*n +j]*x[j];
}
/*Sum for i>j*/
for((j=i+1);j<n;j++){
sum += A[i*n +j]*x[j];
}
//Determine X value for current iteration
x[i] = (b[i]- sum)/A[i*n + i];
/*Find the residual difference using L1-norm*/
if((k>0) && (delta>((fabs(x[i] - x_store)/fabs(x[i]))))){
delta = fabs(x[i] - x_store)/fabs(x[i]);
}
}
k++;
}
/*Print Number of iterations*/
printf("\nNumber of iterations: %d using a tolerance of %f \n",k,TOL);
}
void position_solve(int n,int k,double X[], double x[],double order[])
{
int j, position;
double length = 0;
for (j = 0; j < n; j++) {
//printf("%f ", X[j]);
position = (int)(order[k*n +j]);
length += X[j] + x[position];
printf("Bungee Jumper %i: %lf meters\n",position,length);
/*Reset X vector to zero*/
X[j] = 0;
printf("\n");
}
}
void inverse(int n, double A[],double X[],double b[])
{
int i,j;
double *Inv_A;
ALLOCATE(Inv_A, double, n * n);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i==j){
b[i]=1;
}
else{
b[i]=0;
}
}
iter_solve(n,A,b,X);
for(j=0;j<n;j++){
Inv_A[i*n +j] = X[j];
}
}
printf("\nInverse A = [\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf(" %lf ",A[i*n +j]);
}
printf("\n");
}
printf(" ]\n");
FREE(Inv_A);
}
void swap(double *p1,double *p2)
{ double temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int noofpermutations(int n)
{ int permutations=1,i;
for(i=1;i<=n;i++)
permutations=permutations*i;
return permutations;
}
void next(int n,double a[])
{ int i;
for(i=0;i<n;i++){
if(count < noofpermutations(n)){
a[(count+1)*n + i] = a[count*n +i];
}
}
count++;
}
void permute(int n, double a[])
{ int j;
while(count<noofpermutations(n)){
for(j=0;j<n-1;j++)
{ swap(&a[count*n + j],&a[(count*n) + (j+1)]);
next(n,a);
}
swap(&a[(count*n)],&a[(count*n) + 1]);
next(n,a);
for(j=n-1;j>0;j--)
{ swap(&a[(count*n)+ j],&a[(count*n) + (j-1)]);
next(n,a);
}
swap(&a[(count*n) + (n-1)],&a[(count*n) + (n-2)]);
next(n,a);
}
}
void permutation(int n,double a[])
{
permute(n,a);
count = 0;
allocate.h
/*
* allocate.h
*
* Dynamic memory allocation macros
*/
#ifndef _allocate_h_
#define _allocate_h_
#include <stdio.h>
#include <stdlib.h>
#define ALLOCATE(VAR,TYPE,SIZE) \
{ \
(VAR) = (TYPE *) calloc ((SIZE), sizeof(TYPE)); \
if ((VAR) == NULL) { \
fprintf (stderr, "ALLOCATE: Memory allocation failed (%s:%d) [%d]\n", __FILE__, __LINE__, (SIZE)); \
exit (EXIT_FAILURE); \
} \
}
#define FREE(VAR) \
{ \
free ((VAR)); \
(VAR) = NULL; \
}
#endif
/*
* iter.h
*
* Routine for solving square systems of linear equations with
* multiple right-hand sides AX=B using Gauss-Seidel iterative methods
*/
/* Zero tolerance for double precision */
#define ZERO 1.0E-12
/* Tolerance for iteration relative change */
#define TOL 0.01
/* Maximum number of iterations */
#define MAX_ITER 500
void iter_solve(int n, double A[], double b[], double x[]);
/*
* Iterative solver, x = (b - LU * xp) / D
* Input:
* n = size of matrix A
* A = factorised A matrix, (nxn) stored by row
* b = right-hand side vector, (nx1)
* Output:
* x = solution vector, (nx1)
* Failure scenarios:
* Division by "zero"
*/
When his error occurs in the debugger, it should tell you where you are in the program that it occurs - hopefully this will let you identify which memory location is being corrupted.
Note that address, restart the program in the debugger, set a breakpoint for after the allocations occurs, then set a data breakpoint on that memory location and run to see who's trashing it.
dlls may cause heap corruption if the runtime library for linking of your project differs from the library's