4-dimensional array allocation: access violation - c

I wrote this simple piece of code to dynamically allocate a 4-dimensional array:
#include <stdlib.h>
#include <stdio.h>
int**** alloc() {
int i,j,k;
int ****matrix;
int x,y,z,n_pairs;
x= 62;
y= 45;
z= 28;
n_pairs = 4;
matrix = (int ****) malloc(x*sizeof(int***));
for (i=0; i<x; i++) {
matrix[i] = (int ***) malloc(y*sizeof(int**));
if(matrix[i]==NULL)
return NULL;
for (j=0; j<y; j++) {
matrix[i][j] = (int **) malloc(z*sizeof(int*));
if (matrix[i][j] == NULL)
return NULL;
for (k=0; k<n_pairs; k++) {
matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));
if (matrix[i][j][k] == NULL)
return NULL;
}
}
}
return matrix;
}
void freeMatrix(int ****m) {
int i,j,k;
int x,y,z;
x= 62;
y= 45;
z= 28;
for(i=0; i<x; i++) {
for(j=0; j<y; j++) {
for(k=0; k<z; k++)
free(m[i][j][k]);
free(m[i][j]);
}
free(m[i]);
}
free(m);
}
int main() {
int i,j,k,h;
int ****m = NULL;
m = alloc();
for(i=0;i<62;i++)
for(j=0;j<45;j++)
for(k=0;k<28;k++)
for(h=0;h<4;h++)
printf("%d\t",m[i][j][k][h]);
system("pause");
return 0;
}
the problem is that I this code results in an Access Violation when I try to execute it.
Isn't it the correct way to allocate/free a multidimensional array? If yes, then what is the problem?

One problem is here:
for (k=0; k<n_pairs; k++) { //<----- This should read `k<z'
matrix[i][j][k] = (int *)calloc(n_pairs,sizeof(int));
You probably meant to loop to z, not to n_pairs.

if u make a matrix the correct way is to allocate all the memory u need, then dived it up.
for 2.dim
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
int ** matrix;
int rows = 10;
int colums =10;
matrix = (int**)malloc(rows*sizeof(int*));
matrix[0] = (int*)malloc(rows*colums*sizeof(int));
for(i =1; i<rows;i++)
matrix[i] = &matrix[i-1][colums];
free(matrix[0]);
free(matrix);
return 0;
}
this is for having a continues memory area for the matrix. this can be faster

Related

Segmentation Fault From Using 2D Array in Function (probably)

Edit3: Added Example.
Edit2: So, because I am new to coding in general and because of the current comments,I need to ask, would it be better if I posted the entire code as a comment? (around 90 lines)
So, I have been playing around with dynamic memory allocation and I have a 2D board, witch fills with '.'. Then I import the board in a function, witch checks for available cells (cell with '.'==available). It compiles ok, but when I run it I get
segmentation fault
Here's the code for the board malloc
**board = (char**) malloc(x_input*sizeof(char*));
for(i = 0; i <x_input; i++){
board[i] = (char*) malloc(y_input*sizeof(char));
}
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
Here's the Function
int checker(int x_axis, int y_axis, char **board){
if (board[x_axis][y_axis] == '.'){
return 1;
} else {
return 2;
}
}
And here's the only time(so far) that I call the function
Edit: x_replacement and y_replacement are assigned random values through a rand function
do{
board[x_replacement][y_replacement] = '$';
} while(checker(x_replacement, y_replacement, board) == 2);
EX:
const int MAX_X = 40;
const int MAX_Y = 40;
const int MIN_X = 20;
const int MIN_Y = 20;
int x_input, y_input;
int main(void){
char **board;
int i, j, k, obstacles, enemies, choice;
do{
printf("Enter board size. (Must be between (%d, %d) and (%d, %d))\n:", MIN_X, MIN_Y, MAX_X, MAX_Y);
scanf("%d%d", &x_input, &y_input);
}while ((x_input <= MIN_X && x_input >= MAX_X) && (y_input <= MIN_Y && y_input >= MAX_Y));
*board = malloc(sizeof(char[x_input][y_input]));
assert(*board != NULL);
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
return 0;
}
I approached this from a different perspective, thanks to Ludin's and Some Programmer Dude's links so the result, witch works is the following:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void arr_alloc (size_t x, size_t y, char(**board)[x][y])
{
*board= malloc( sizeof(char[x][y]) );
assert(*board!= NULL);
}
void arr_fill (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
array[i][j] = '.';
}
}
}
void arr_print (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int main (void)
{
int x,y;
char (*board)[x][y];
printf("enter dimentions: \n");
scanf("%d%d", &x, &y);
arr_alloc(x, y, &board);
arr_fill(x, y, *board);
arr_print(x, y, *board);
free(board);
return 0;
}

How to change the content of a 2d array in C?

I am working on a problem where I have to transpose a matrix. I am passing the address of the original matrix, but once I execute the function it does not change!
I have tried to add a * infront of matrix in the transpose function, thinking that it will be pointing to the whole 2d array, but it did not work.
#include<stdio.h>
#include <stdlib.h>
void transpose(int *r,int *c, int **matrix);
void printMatrix(int r,int c, int **matrix){
for(int i=0;i<r;i++){
for(int j=0;j<c;j++)
printf("%2d ",matrix[i][j]);
printf("\n");
}
}
int main() {
int **matrix;
int r =3;
int c =2;
matrix = (int**) malloc(r*sizeof(int*));
for(int i=0;i<r;i++)
matrix[i] = (int*) malloc(c*sizeof(int));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++)
matrix[i][j] = (3*i+2*j)%8+1;
}
printf("Before transpose:\n");
printMatrix(r,c,matrix);
transpose(&r, &c ,matrix);
printMatrix(r,c,matrix);
return 0;
}
void transpose(int *r,int *c, int **matrix){
int newR = *c;
int newC = *r;
int **newMatrix;
newMatrix = (int**) malloc(newR*(sizeof(int*)));
for(int i=0; i<newR;i++)
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
for(int i=0; i<newR; i++)
for(int j=0;j<newC;j++)
newMatrix[i][j] = matrix[j][i];
*c = newC;
*r = newR;
matrix = (int**) malloc((*r)*sizeof(int*));
for(int i=0;i<*r;i++)
matrix[i] = (int*) malloc((*c)*sizeof(int));
for(int i=0; i<newR; i++){
for(int j=0;j<newC;j++){
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}
}
I have this matrix
1 3
4 6
7 1
and want to get
1 4 7
3 6 1
however I am getting
1 3 0
1 4 0
It looks like all you forgot to do was actually use the transposed matrix. All I did was change the function signature and return the matrix you had already allocated and manipulated, and I got the output you were looking for.
#include <stdio.h>
#include <stdlib.h>
int** transpose(int *r,int *c, int **matrix);
void printMatrix(int r, int c, int **matrix) {
for (size_t i = 0; i < r; ++i){
for (size_t j = 0; j < c; ++j) {
printf("%2d ",matrix[i][j]);
}
printf("\n");
}
}
int main()
{
int r = 3;
int c = 2;
int **matrix = calloc(sizeof(int*), r);
for (size_t i = 0; i < r; ++i) {
matrix[i] = calloc(sizeof(int), c);
}
for (size_t i = 0; i < r; ++i) {
for (size_t j = 0; j < c; ++j) {
matrix[i][j] = (3 * i + 2 * j) % 8 + 1;
}
}
printf("Before transpose:\n");
printMatrix(r, c, matrix);
int** newMatrix = transpose(&r, &c ,matrix);
printMatrix(r, c, newMatrix);
return EXIT_SUCCESS;
}
int** transpose(int *r, int *c, int **matrix) {
int newR = *c;
int newC = *r;
int **newMatrix = calloc((sizeof(int*)), newR);
for (size_t i = 0; i < newR; ++i) {
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
}
for (size_t i = 0; i < newR; ++i) {
for (size_t j = 0; j < newC; ++j) {
newMatrix[i][j] = matrix[j][i];
}
}
*c = newC;
*r = newR;
matrix = calloc(sizeof(int*), *r);
for (size_t i = 0; i < *r; ++i) {
matrix[i] = calloc(sizeof(int), *c);
}
for (size_t i = 0; i < newR; ++i) {
for (size_t j = 0; j < newC; ++j) {
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}
return newMatrix;
}
Output:
1 4 7
3 6 1
I changed a few things, especially because I prefer using calloc over malloc, since it zeroes out the newly-allocated memory, and there is a dedicated parameter for the size of the requested memory, which I think semantically is a better idea.
As a side note, you don't have to cast the result of malloc in C. I tend to feel more strongly about that than other people, I think, because code noise, especially when you're working in C is one of the worst things you can do to yourself. This is a pretty good example of that, since all I did was reformat your code and the answer was right there. Don't be stingy with the whitespace, either; it really does make a difference.
Anyways, I hope this helped somewhat, even if you literally had basically everything done.
#include<stdio.h>
#include <stdlib.h>
void transpose(int *r,int *c, int ***matrix);
void printMatrix(int r,int c, int **matrix){
int i=0,j=0;
for(i=0;i<r;i++){
for(j=0;j<c;j++)
printf("%2d ",matrix[i][j]);
printf("\n");
}
}
int main() {
int **matrix;
int r =3;
int c =2;
int i=0,j=0;
matrix = (int**) malloc(r*sizeof(int*));
for(i=0;i<r;i++)
matrix[i] = (int*) malloc(c*sizeof(int));
for(i=0;i<r;i++){
for(j=0;j<c;j++)
matrix[i][j] = (3*i+2*j)%8+1;
}
printf("Before transpose:\n");
printMatrix(r,c,matrix);
transpose(&r, &c, &matrix);
printMatrix(r,c,matrix);
return 0;
}
void transpose(int *r,int *c, int ***matrix){
int newR = *c;
int newC = *r;
int **newMatrix;
int i=0,j=0;
newMatrix = (int**) malloc(newR*(sizeof(int*)));
for(i=0; i<newR;i++)
newMatrix[i] = (int*) malloc(newC*(sizeof(int)));
for(i=0; i<newR; i++)
for(j=0;j<newC;j++) {
newMatrix[i][j] = (*matrix)[j][i];
}
*c = newC;
*r = newR;
// free matrix..
*matrix = newMatrix;
/*matrix = (int**) malloc((*r)*sizeof(int*));
for(i=0;i<*r;i++)
matrix[i] = (int*) malloc((*c)*sizeof(int));
for(i=0; i<newR; i++){
for(j=0;j<newC;j++){
matrix[i][j] = newMatrix[i][j];
}
printf("\n");
}*/
}

C pointer dereference error

Suppose I have the following code (example):
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void Ex(void *ret, int ret_len, int choice){
if(choice==1){
int *ret = ret;
for(int i=0; i<ret_len; i++){
*(ret+i) = i;
}
} else {
int **ret = ret;
for(int i=0; i<ret_len; i++){
for(int j=0; j<ret_len; j++){
*(*(ret+i)+j) = i*j;
}
}
}
}
int main()
{
int m[10];
Ex(m,10,1);
printf("%i",m[3]);
return 0;
}
The goal of the function is to take a pointer to preallocated memory of a one or two dimensional array.
When compiled and executed the code works when choice==1, otherwise, if I run
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void Ex(void *ret, int ret_len, int choice){
if(choice==1){
int *ret = ret;
for(int i=0; i<ret_len; i++){
*(ret+i) = i;
}
} else {
int **ret = ret;
for(int i=0; i<ret_len; i++){
for(int j=0; j<ret_len; j++){
*(*(ret+i)+j) = i*j;
}
}
}
}
int main()
{
int m[100];
Ex(m,10,2);
printf("%i", m[3][5]);
return 0;
}
no output is ever produced and the code seems to run forever (note choice is now not 1 and m is the proper size)
I am under the impression that the casting in Ex should change the shape of the array and allow main to index into it as if it were 2d but neither indexing into it as if it were 1d nor 2d work.
Having looked at the comments on the question and some answers this is what I have gathered for your requirements.
You need a generic function that takes an array of choice dimensions and initializes it with some values.
This can suit your purpose.
void Ex(void *_ret, int ret_len, int choice){
if(choice==1){
int *ret = _ret;
int i;
for(i=0; i<ret_len; i++){
ret[i] = i;
}
} else {
int (*ret)[ret_len] = _ret;
int i, j;
for(i=0; i<ret_len; i++){
for(j=0; j<ret_len; j++){
ret[i][j] = i*j;
}
}
}
}
Now this is how you can call it
int main(void) {
int first[10];
Ex(first, 10, 1);
int second[20][20];
Ex(second, 20, 2);
printf("first[4] = %d\n", first[4]);
printf("second[3][4] = %d\n", second[3][4]);
}
You can see the Demo here
because ret if of type int *, but the else part is:
for(int i=0; i<ret_len; i++){
for(int j=0; j<ret_len; j++){
*(*(ret+i)+j)=i*j;
}
}
which needs ret of type int **. and this causes the error.
The way to resolve the problem is to use void *. that is one way to use generics in C.
Take a look at qsort in C.
void Ex(void *_ret, int ret_len, int choice){
if(choice==1){
int *ret = (int *)_ret; // <---- type conversion
for(int i=0; i<ret_len; i++){
*(ret+i) = i;
}
} else {
int **ret = (int **)_ret; // <---- type conversion
for(int i=0; i<ret_len; i++){
for(int j=0; j<ret_len; j++){
*(*(ret+i)+j) = i*j;
}
}
}
}
The closest thing with least change of your existing code I came up with is:
#include <stdio.h>
void Ex(int * ret, int ret_len, int choice){
if(choice==1){
for(int i=0; i<ret_len; i++){
*(ret+i)=i;
}
}else{
for(int i=0; i<ret_len; i++){
for(int j=0; j<ret_len; j++){
*(ret + i*ret_len + j) = i*j;
}
}
}
}
int main() {
int anint[10][10];
Ex(anint, 10, 2);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {printf("%d\n", anint[i][j]);}
}
}
Basically, I mannually manipulate the offset within the Ex function. and I take the assumption that the length of the two dimensions are always the same.
A more "conventioal way" would be a true 2-dimentional array in which each element is malloc independently. Thus, the element of the first level array can be casted by force to a pointer and be dereferenced in the second level. But I am reluctant to call malloc too many times.
I hope this can solved your problem.

crash on trying to reallocate a pointer using pointer to this pointer

I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).

stack overflow unless printf under recursion

This code below is the code for finding the determinant for 3x3 matrix (this code is intended for nxn matrix, but for the sample, I used 3x3), using recursive
The result is working fine, but I wonder what errors in this code make this must be the printf("\n") before calling the sub-function (itself) or else it will return the error 0xc0000fd (stack overflow).
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#define size 3
void trimarray(int**rrayrc,int**rrayout, int dim,int cuti,int cutj)
{
int i, j;
int ti = 0,tj;
for(i = 0; i<dim; i++)
{
tj = 0;
for(j = 0; j< dim; j++)
{
if(!((i==cuti)||(j==cutj)))
{
rrayout[ti][tj] = rrayrc[i][j];
}
if(j!=cutj) {tj++;}
}
if(i!=cuti) {ti++;}
}
}
void initializearray(int** rray,int dim)
{
int i, j;
for(i = 0; i<dim; i++)
{
for(j = 0; j<dim; j++)
{
rray[i][j] = 0;
}
}
}
int det(int** rray, int dim)
{
int i,j;
int cut[dim-1][dim-1];
int* cutp[i];
int mul = 1,sum=0;
if(dim >1)
{
for(i = 0; i<dim-1; i++)
{
cutp[i] = cut[i];
}
initializearray(cutp,dim-1);
for(i = 0; i<dim; i++)
{
printf("\n",dim); //<< Without this the program won't work
trimarray(rray,cutp,dim,0,i);
sum+=det(cutp,dim-1)*mul*rray[0][i];
mul = 0-mul;
}
return sum;
}
else
{
return rray[0][0];
}
}
int main()
{
int test[size][size] = {2,-3,-2,-6,3,3,-2,-3,-2};
int* testpntr[size];
int i,deter;
for(i = 0; i<size; i++)
{
testpntr[i] = test[i];
}
deter = det(testpntr,size);
printf("[%d]",deter);
getch();
return 0;
}
The answers will be dearly appreciated.
int* cutp[i]; is undefined behavior since i is uninitialized at this stage. You have no idea what is the size of cutp array.

Resources