malloc'ed 3d array generates Data Access Violation - c

I have a malloc'ed 3d array of doubles in C that is generating a Data Access Violation error when accessed via indexes.
The allocation function: (Simplified version not checking for nulls or freeing if errors)
#define DIMENSIONA 50
#define DIMENSIONB 30
#define DIMENSIONC 2
double *** Array;
void InitialiseDataStructure(void)
{
int Counter = 0;
int PointCounter = 0;
Array = (double ***)malloc(DIMENSIONA * (sizeof(double**)));
for (Counter = 0; Counter < DIMENSIONA; Counter++)
{
Array[Counter] = (double **)malloc(DIMENSIONB * sizeof(double *));
for (PointCounter = 0; PointCounter < DIMENSIONB; PointCounter++)
{
Array[Counter][PointCounter] = (double *)malloc(DIMENSIONC * sizeof(double));
}
}
}
The array is then accessed like this:
Array[x][y][z] = 0;
This generates a data access violation error and terminates the program.
I have read and tried and come to the conclusion - I am dumb.
Please help!!!

What is POINTS_PER_GEOFENCE in the following for loop?
for (PointCounter = 0; PointCounter < POINTS_PER_GEOFENCE; PointCounter++)
Shouldn't that be
Array = malloc(DIMENSIONA * (sizeof(double**)));
for (Counter = 0; Counter < DIMENSIONA; Counter++) {
Array[Counter] = malloc(DIMENSIONB * sizeof(double *));
for (PointCounter = 0; PointCounter < DIMENSIONB; PointCounter++) {
Array[Counter][PointCounter] = malloc(DIMENSIONC * sizeof(double));
}
}
Note:
Read this for casting malloc()'s return value.
You need to check whether the malloc()'s returned success and failure before using that.

Related

C Keep Getting Double Free, despite trying to free in same form as allocation

Hey I'm trying to do a simple machine learning application for school but I keep getting double free for some reason I cannot even fathom.
float * evaluate(Network net,float * in)
{
int i,j;
float * out;
Neuron cur_neu;
for(i=0,j=0;i<net.n_lay;i++) j = net.lay_sizes[i]>j?net.lay_sizes[i]:j; //Calculating the maximum lay size for output storage
out = (float *) malloc(j*sizeof(float));
for(i=0;i<net.n_lay;i++) //Cycling through layers
{
for(j=0;j<net.lay_sizes[i];j++) //Cycling through Neurons
{
cur_neu=net.matrix[i][j];
out[j] = cur_neu.af(cur_neu.w,in,net.lay_sizes[i-1]); //Storing each answer in out
}
for(j=0;j<net.lay_sizes[i];j++) in[j] = out[j]; //Transfering answers to in
}
return out;
}
float loss(Network net, float **ins_orig, int t_steps)
{
float **profecies;
float st = .5f;
int d_steps = 4;
int t, i, j;
int out_size = net.lay_sizes[net.n_lay - 1];
int in_size = net.lay_sizes[0];
float out = 0.0f;
float **ins;
/*
d_steps = Divination Steps: Number of time steps forward the network has to predict.
The size of the output layer must be d_steps*#ins (deconsidering any conceptual i/os)
t_steps = Total of Steps: Total number of time steps to simulate.
*/
//Copying ins
ins = (float **)malloc(t_steps * sizeof(float *));
for (i = 0; i < t_steps; i++) //I allocate memory for and copy ins_orig to ins here
{
ins[i] = (float *)malloc(in_size * sizeof(float));
for (j = 0; j < in_size; j++)
ins[i][j] = ins_orig[i][j];
}
//
profecies = (float **)malloc(t_steps * sizeof(float *));
for (t = 0; t < t_steps; t++)
{
profecies[t] = evaluate(net, ins[t]);
/*
Profecy 0:
[[a1,b1,c1,d1]
[e1,f1,g1,h1]
[i1,j1,k1,l1]]
Profecy 1:
[[e2,f2,g2,h2]
[i2,j2,k2,l2]
[m2,n2,o2,q2]]
Verification for:
t=0:
loss+= abs(a1-ins[t][0]+b2-ins[t][1]...)
t=1:
t=0:
loss+= abs(e1-ins[t][0]+f2-ins[t][1]...)
*/
for (i = 0; i < d_steps; i++) //i is distance of prediction
{
if (i <= t) // stops negative profecy indexing
{
for (j = 0; j < in_size; j++)
{
out += (ins[t][j] - profecies[t-i][j+in_size*i]) * (ins[t][j] - profecies[t-i][j+in_size*i]) * (1 + st*i); //(1+st*i) The further the prediction, the bigger reward
}
}
}
}
//Free ins
for (i = 0; i < t_steps; i++) //I try to free it here, but to no avail
{
free(ins[i]);
}
free(ins);
return out;
}
I realize it's probably something very obvious but, I can't figure it out for the life of me and would appreciate the help.
Extra details that probably aren't necessary:
evaluate just passes the input to the network (stored in ins) and returns the output
both inputs and outputs are stored in float "matrixes"
Edit: Added evaluate
In your loss() you allocate the same number of floats for each ins:
ins[i] = (float *)malloc(in_size * sizeof(float));
In your evaluate() you calculate the longest lay_size, indicating that it may NOT be net.lay_sizes[0]:
for(i=0,j=0;i<net.n_lay;i++) j = net.lay_sizes[i]>j?net.lay_sizes[i]:j; //Calculating the maximum lay size for output storage
Then you are writing out-of-bounds here:
for(j=0;j<net.lay_sizes[i];j++) in[j] = out[j]; //Transfering answers to in
From that point, your memory is corrupted.

Why does this introduce a memory leak?

I am implementing an Ant Colony Optimization for the Set Covering Problem in C. In my code, I have found a function that causes a memory leak. I am pretty sure this function is the cause of the memory leak, since I have ruled out other functions by testing. Only, I don't understand why this function introduces a memory leak.
To understand this function, I'll describe the Ant struct first. The Ant struct looks like this:
struct Ant {
int* x;
int* y;
int fx;
int** col_cover;
int* ncol_cover;
int un_rows;
double* pheromone;
}
typedef struct Ant ant_t;
The pointers in this struct (such as x, y, col_cover, etc.) are initialized using malloc and freed at the end of the program. Now, the function causing the memory leak is the following:
void localSearch(ant_t* ant) {
int improvement = 1;
ant_t* antcpy = (ant_t*) malloc(sizeof(ant_t));
initAnt(antcpy);
copyAnt(ant, antcpy);
while (improvement) {
improvement = 0;
for (int i = 0; i < inst->n; i++) {
if (antcpy->x[i]) {
removeSet(inst, antcpy, i);
while (!isSolution(antcpy)) {
constructSolution(antcpy);
}
if (antcpy->fx < ant->fx) {
copyAnt(antcpy, ant);
improvement = 1;
eliminate(ant);
} else {
copyAnt(ant, antcpy);
}
}
}
}
free((void*) antcpy);
}
First, I create another instance of the Ant struct (antcpy), using the initAnt function. The copyAnt function does a deep copy of one Ant struct to another Ant struct. My reason for doing a deep copy is the following; I am changing the antcpy and then comparing it to ant. If it turns out better (antcpy->fx < ant->fx), ant is replaced by antcpy. If it turns out worse, antcpy is restored to the values of ant.
These functions are given below:
void initAnt(ant_t* ant) {
ant->x = (int*) malloc(inst->n * sizeof(int));
ant->y = (int*) malloc(inst->m * sizeof(int));
ant->col_cover = (int**) malloc(inst->m * sizeof(int*));
ant->ncol_cover = (int*) malloc(inst->m * sizeof(int));
ant->pheromone = (double*) malloc(inst->n * sizeof(double));
for (int i = 0; i < inst->m; i++) {
ant->col_cover[i] = (int*) malloc(inst->ncol[i] * sizeof(int));
}
}
void copyAnt(ant_t* from, ant_t* to) {
to->fx = from->fx;
to->un_rows = from->un_rows;
for (int i = 0; i < inst->n; i++) {
to->x[i] = from->x[i];
to->pheromone[i] = from->pheromone[i];
}
for (int i = 0; i < inst->m; i++) {
to->y[i] = from->y[i];
to->ncol_cover[i] = from->ncol_cover[i];
for (int j = 0; j < inst->ncol[i]; j++) {
to->col_cover[i][j] = from->col_cover[i][j];
}
}
}
I don't really see why this code causes a memory leak, since I free antcpy at the end of the localSearch function. So, why does this code introduce a memory leak and how can I fix it?
You will have to implement a function freeAnt that before free((void*) antcpy); will release all memory that was allocated in initAnt.
void freeAnt(ant_t* ant) {
for (int i = 0; i < inst->m; i++) {
free(ant->col_cover[i]);
}
free(ant->pheromone);
free(ant->ncol_cover);
free(ant->col_cover);
free(ant->y);
free(ant->x);
}

C Array being overwritten? [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 6 years ago.
Improve this question
When I run this program : http://hastebin.com/asorawoluw.m
I get this error in GDB :
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401f91 in resoudre (baie=...) at lineaire.c:291
291 printf("type[%d] : %d\n", i, helper_glpk.col_bounds[i]->type);
When i ask gdb to print iI get :
$1 = 1
So the first iteration is failing, but I'm sure I did write into the first case of helper_glpk.col_bounds at the line 200-204 and I did malloc so there's no way (I think ?) that my data is being overwritten or deleted.. so I don't understand why I get this error.
Edit : here's the minimal code :
My structs :
typedef struct Bounds Bounds;
struct Bounds
{
int type;
double lb;
double ub;
};
typedef struct HelperGlpk HelperGlpk;
struct HelperGlpk
{
double *matrix_coefs;
double *obj_coefs;
Bounds **row_bounds;
Bounds **col_bounds;
int *column_of_coef;
int *row_of_coef;
int cpt_coef;
int cpt_contrainte;
};
My functions to generates constraint :
void genere_contrainte_1(int i, int j, HelperGlpk *helper_glpk, Baie baie){
helper_glpk->col_bounds[index_ouverture_serveur(i)]->type = GLP_DB;
helper_glpk->col_bounds[index_ouverture_serveur(i)]->lb = 0;
helper_glpk->col_bounds[index_ouverture_serveur(i)]->ub = 1;
helper_glpk->cpt_coef++;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->type = GLP_LO;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->lb = 0;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->ub = 0;
helper_glpk->cpt_coef++;
}
and the main program is :
void resoudre(Baie baie){
glp_prob *lp;
const int nbr_rows = baie.nbr_client + baie.nbr_serveur * baie.nbr_client; // nombre de contrainte
const int nbr_colums = baie.nbr_serveur + baie.nbr_serveur * baie.nbr_client; // nombre de variable
const int nbr_coefs = 3 * baie.nbr_serveur * baie.nbr_client;
int i, j;
HelperGlpk helper_glpk;
helper_glpk.matrix_coefs = malloc((nbr_coefs + 1) * sizeof(double));
helper_glpk.matrix_coefs[0] = 0;
helper_glpk.obj_coefs = malloc((nbr_colums + 1) * sizeof(double));
helper_glpk.obj_coefs[0] = 0;
helper_glpk.column_of_coef = malloc((nbr_colums + 1) * sizeof(int));
helper_glpk.column_of_coef[0] = 0;
helper_glpk.row_of_coef = malloc((nbr_rows + 1) * sizeof(int));
helper_glpk.row_of_coef[0] = 0;
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds *));
for (int index = 0; index <= nbr_colums; index++)
{
helper_glpk.col_bounds[index] = malloc(sizeof(Bounds));
}
helper_glpk.row_bounds = malloc((nbr_rows + 1) * sizeof(Bounds *));
for (int index = 0; index <= nbr_rows; index++)
{
helper_glpk.row_bounds[index] = malloc(sizeof(Bounds));
}
helper_glpk.cpt_coef = 1;
for(i = 1; i <= baie.nbr_serveur; i++)
for(j = 1; j <= baie.nbr_client; j++)
genere_contrainte_1(i, j, &helper_glpk, baie);
for(i = 1; i <= nbr_colums; i++)
printf("type[%d] : %d\n", i, helper_glpk.col_bounds[i]->type);
for(j = 1; j <= baie.nbr_client; j++)
genere_contrainte_2(j, &helper_glpk, baie.nbr_serveur);
The error I get is while I try to printf after the call to generate_contrainte_1
This code is wrong:
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds));
You need to fix it with (provided you need nbr_colums + 1 elements):
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds *));
for (int index = 0; index < nbr_colums + 1; index++)
{
helper_glpk.col_bounds[index] = malloc(sizeof(Bounds));
}
I have not checked the rest of the code, there could be other errors.
Edit: maybe you don't need the for loop depending on what your genere_contrainte_1 does, but you need to correct your malloc with the right sizeof.
Edit2: I read your genere_contrainte_1, you definitely need all these mallocs. But I really doubt you need row_bounds and col_bounds to be Bounds **, it seems to me Bounds * would have been fine, and that way a single malloc for each field would be enough.

Connect-N Board Game, crashing when Width is >> Height

I'm in the process of coding a Connect-N board game, and I'm almost finished and have gone through troubleshooting. My problem is now after changing some stuff my game crashes when the computer plays its move if the Width is too much greater than the height. There are two functions involved here, so I will paste them both.
Board
*AllocateBoard(int columns, int rows)
{
int **array= malloc(sizeof(int *) *columns);
int r = 0;
for ( r = 0; r < columns; ++r)
{
array[r] = malloc(sizeof(int) * rows);
}
int j = columns - 1;
int k = rows - 1;
int m = 0;
int n = 0;
for ( m = 0; m < j; ++m)
{
for ( n = 0; n < k; ++n)
{
array[m][n] = 0;
}
}
Board *board = malloc(sizeof(Board));
board->columns = columns;
board->rows = rows;
board->spaces = array;
return board;
}
This first function allocates the board to be a matrix Width * Height that the user passes in via the command line. It then initializes every space on the board to be zero, and then stores the columns, rows, and spaces into a Board structure that I've created. It then returns the board.
int
computerMakeMove(Board *board)
{ int RandIndex = 0;
int **spaces = board->spaces;
int columns = board->columns;
int *arrayoflegalmoves = malloc(sizeof(int) * (columns));
int columncheck = 0;
int legalmoveindex = 0;
while (columncheck <= columns - 1)
{
if (spaces[columncheck][0] == 0)
{
arrayoflegalmoves[legalmoveindex] = columncheck;
++legalmoveindex;
++columncheck;
}
else
{
++columncheck;
}
arrayoflegalmoves = realloc(arrayoflegalmoves, (legalmoveindex) * sizeof(int));
}
if (legalmoveindex == 1)
{
return arrayoflegalmoves[0];
}
else
{
RandIndex = rand() % (legalmoveindex);
return arrayoflegalmoves[RandIndex];
}
}
This second function is designed to make the computer randomly pick a column on the board. It does this by checking the value of the top row in each column. If there is a zero there, it will store this value in an array of legal moves, and then it increments the legalmoveindex. If there isn't, it skips the column and checks the next. It ends when it gets finished checking the final column. If there is only one legal move, it will play it. If there are more, it will select a random index from the array of legal moves (I run srand in the main) and then return that value. It will only ever attempt to play on a legal board, so that's not the problem. I am pretty confident the problem occurs in this function, however, as I call the functions as follows
printf("Taking the computers move.\n");
{printf("Taking computer's move.");
computermove = computerMakeMove(playerboard);
printf("Computer's move successfully taken.\n");
playerboard = MakeMove(playerboard, computermove, player);
printf("Computer's board piece successfully played.\n");
system("clear");
displayBoard(playerboard);
...;
}
and it prints
Aborted (core dumped)
immediately after it prints
"Taking computer's move."
Once again, my question is: why is my program crashing if the width is larger than the height when the computer plays?
Thanks.
Edit: I found the solution and I am stupid.
I realloc'd during the while loop.
The realloc should be the first thing outside of the while loop.
The answer for any future programmers who may have this problem:
Notice the
while (columncheck <= columns - 1)
{
if (spaces[columncheck][0] == 0)
{
arrayoflegalmoves[legalmoveindex] = columncheck;
++legalmoveindex;
++columncheck;
}
else
{
++columncheck;
}
arrayoflegalmoves = realloc(arrayoflegalmoves, (legalmoveindex) * sizeof(int));
}
has a realloc inside of it. The realloc should be moved to immediately outside of it, like so
while (columncheck <= columns - 1)
{
if (spaces[columncheck][0] == 0)
{
arrayoflegalmoves[legalmoveindex] = columncheck;
++legalmoveindex;
++columncheck;
}
else
{
++columncheck;
}
}
arrayoflegalmoves = realloc(arrayoflegalmoves, (legalmoveindex) * sizeof(int));
it is unusual to have the columns be the first index in an array.
having the first index of an array be columns leads to confusion
// suggest using camel case for all variable names, for readability
Board *AllocateBoard(int columns, int rows)
{
int **array= malloc(sizeof(int *) *columns); // add check that malloc successful
int r = 0;
for ( r = 0; r < columns; ++r)
{
array[r] = malloc(sizeof(int) * rows); // <-- add: check that malloc successful
}
int j = columns - 1; // this results in last column not initialized
int k = rows - 1; // this results in last row of each column not initialized
int m = 0; // column loop counter
int n = 0; // row loop counter
for ( m = 0; m < j; ++m)
{
for ( n = 0; n < k; ++n)
{
array[m][n] = 0;
}
}
Board *board = malloc(sizeof(Board)); // <-- add: check if malloc successful
board->columns = columns;
board->rows = rows;
board->spaces = array;
return board;
} // end function: AllocateBoard
// why is this only looking at the first row of each column?
int computerMakeMove(Board *board)
{
int RandIndex = 0;
int **spaces = board->spaces;
int columns = board->columns;
int *arrayoflegalmoves = malloc(sizeof(int) * (columns)); // <-- add check that malloc successful
int columncheck = 0;
int legalmoveindex = 0;
while (columncheck <= columns - 1)// should be: for(; columncheck < columns; columncheck++ )
{
if (spaces[columncheck][0] == 0)
{ // then first row of column is zero
arrayoflegalmoves[legalmoveindex] = columncheck;
++legalmoveindex;
++columncheck; // <-- remove this line
}
else // remove this 'else' code block
{
++columncheck;
} // end if
arrayoflegalmoves = realloc(arrayoflegalmoves, (legalmoveindex) * sizeof(int));
// <-- 1) use temp int*, in case realloc fails
// <-- 2) if realloc successful, update arrayoflegalmoves
// <-- 3) the code is not checking each row of each column,
// so the original malloc is more than plenty
// so why bother to realloc
// <-- 4) if legalmoveindex is 0 then realloc returns NULL
} // end while
// in following, what about when zero moves found? probably should return NULL
if (legalmoveindex == 1)
{ // only one column[row0] found to contain 0
return arrayoflegalmoves[0];
}
else
{
RandIndex = rand() % (legalmoveindex);
return arrayoflegalmoves[RandIndex]; // if zero moves found, this returns a
// de-reference to address 0
// which would result in a seg fault event
} // end if
} // end function: computerMakeMove

C Memory Management Issue

I have traced an EXC_BAD_ACCESS to the following allocation and deallocation of memory. It involves the accelerate framework in Xcode. The main issue is that this code is in a loop. If i force the loop to only iterate once then it works fine. But when it loops (7 times) it causes an error on the second iteration. Does any of this look incorrect?
EDIT: *added actual code. This segment runs if I remove certain parts and such but seems to have poor memory management which results in issues
#import <Foundation/Foundation.h>
#include <math.h>
#include <Accelerate/Accelerate.h>
for(int i = 0; i < 8; i++)
{
int XX[M][m]; //M and m are just 2 ints
for(int kk = 0; kk < M; kk++)
{
for (int kk1 = 0; kk1 < m; kk1++)
{
XX[kk][kk1] = [[x objectAtIndex: (kk + kk1 * J)] intValue]; //x is a NSMutableArray of NSNumber objects
}
}
double FreqRes = (double) freqSamp/n;
NSMutableArray *freqs = [[NSMutableArray alloc] initWithCapacity: round((freqSamp/2 - FreqRes) - 1)];
int freqSum = 0;
for(double i = -1 * freqSamp/2; i < (freqSamp/2 - FreqRes); i+= FreqRes)
{
[freqs addObject: [NSNumber numberWithInt: i]];
if(i == 0)
{
freqSum++;
}
}
int num = [x count];
int log2n = (int) log2f(num);
int nOver2 = n / 2;
FFTSetupD fftSetup = vDSP_create_fftsetupD (log2n, kFFTRadix2);
double ffx[num];
DSPDoubleSplitComplex fft_data;
fft_data.realp = malloc(nOver2 * sizeof(double)); //Error usually thrown on this line in the second iteration. Regardless of what I put there. If I add an NSLog here it throws the error on that NSLog
fft_data.imagp = malloc(nOver2 * sizeof(double));
for (int i = 0; i < n; ++i)
{
ffx[i] = [[x objectAtIndex:i] doubleValue];
}
vDSP_ctozD((DSPDoubleComplex *) ffx, 2, &fft_data, 1, nOver2);
vDSP_fft_zripD (fftSetup, &fft_data, 1, log2n, kFFTDirection_Forward);
for (int i = 0; i < nOver2; ++i)
{
fft_data.realp[i] *= 0.5;
fft_data.imagp[i] *= 0.5;
}
int temp = 1;
ffx[0] = abs(fft_data.realp[0]);
for(int i = 1; i < nOver2; i++)
ffx[i] = sqrt((fft_data.realp[i] * fft_data.realp[i]) + (fft_data.imagp[i] * fft_data.imagp[i]));
ffx[nOver2] = abs(fft_data.imagp[0]);
for(int i = nOver2-1; i > 0; i--)
{
ffx[nOver2 + temp] = sqrt((fft_data.realp[i] * fft_data.realp[i]) + (fft_data.imagp[i] * fft_data.imagp[i]));
temp++;
}
//clear Fxx and freqs data
vDSP_destroy_fftsetupD(fftSetup);
free(fft_data.imagp);
free(fft_data.realp);
[freqs release];
}
Your problem could be that you are casting malloc to a value. As you're tagging this c, I'm assuming that you are compiling in c in which case you should see this answer to a previous question as to why casting with malloc is bad:
https://stackoverflow.com/a/1565552/1515720
you can get an unpredictable runtime error when using the cast without including stdlib.h.
So the error on your side is not the cast, but forgetting to include stdlib.h. Compilers may assume that malloc is a function returning int, therefore converting the void* pointer actually returned by malloc to int and then to your your pointer type due to the explicit cast. On some platforms, int and pointers may take up different numbers of bytes, so the type conversions may lead to data corruption.
Regardless though, as the answer says, YOU SHOULD NOT BE CASTING MALLOC RETURNS, because void*'s are safely implicitly converted to whatever you are assigning it to.
As another answerer stated:
vDSP_destroy_fftsetupD(fftSetup);
Could be also free'ing the memory you allocated on accident.
Any chance the destructor of DSPDoubleSplitComplex is freeing up those two allocated blocks?
It could also be that you are only allowed to call vDSP_create_fftsetupD and vDSP_destroy_fftsetupD once during your process's lifetime

Resources