Segmentation fault when freeing my matrix - c

I'm using code::blocks.
Code sends a seg fault when freeing the matrix after 2-3 iterations in dealloc_mat.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int **_mat;
int _lines, _columns;
void alloc_mat();
void dealloc_mat();
int main(int argc, char *argv[])
{
_lines = 31, _columns = 22;
alloc_mat();
dealloc_mat();
return 0;
}
void alloc_mat()
{
int i, row, col;
_mat = malloc(sizeof(int *) * _lines);
for(i = 0 ; i < _lines ; i++)
{
int *tmpMatrix = malloc(sizeof(int) * _columns);
_mat[i] = &tmpMatrix[i];
}
for(row = 0 ; row < _lines ; row++)
{
for(col = 0 ; col < _columns ; col++)
{
_mat[row][col] = 0;
}
}
}
void dealloc_mat()
{
int row;
for(row = 0; row < _lines; row++)
{
free(_mat[row]);
}
free(_mat);
}

Here's the bug:
_mat[i] = &tmpMatrix[i];
Should be
_mat[i] = &tmpMatrix[0];
or better
_mat[i] = tmpMatrix;

The problem is that you're not allocating it correctly. This:
for(i = 0 ; i < _lines ; i++)
{
int *tmpMatrix = malloc(sizeof(int) * _columns);
_mat[i] = &tmpMatrix[i];
}
should be this:
for(i = 0 ; i < _lines ; i++)
{
_mat[i] = malloc(sizeof(int) * _columns);
}
Further, _mat, _lines and _columns are reserved identifiers in C, and you shouldn't use them. Any identifier beginning with an underscore with file scope in the ordinary (i.e. _mat) or tag (i.e. struct _mat) namespaces is reserved.

Here are a couple of functions used to allocate memory for strings, arrays of strings actually, you can easily modify them for your purposes:
char **strings; // created with global scope (before main())
void allocMemory(int numStrings, int max)
{
int i;
strings = malloc(sizeof(char*)*(numStrings+1));
for(i=0;i<numStrings; i++)
strings[i] = malloc(sizeof(char)*max + 1);
}
void freeMemory(int numStrings)
{
int i;
for(i=0;i<numStrings; i++)
if(strings[i]) free(strings[i]);
free(strings);
}
Here is how the above would be modified (and used) for ints: (note, it is really just recognizing the differences in sizeof(type))
Note also: using malloc() does not initialize values. If you want to guarantee an initial value for each element (eg. 0), you can use calloc() instead.
void allocMemoryInt(int rows, int cols);
void freeMemoryInt(int numStrings);
int **array;
int main(void)
{
allocMemoryInt(10, 3);
freeMemoryInt(10);
return 0;
}
void allocMemoryInt(int rows, int cols)
{
int i;
array = malloc(sizeof(int *)*(rows)); //create memory for row pointers
for(i=0;i<rows; i++)
array[i] = malloc(sizeof(int)*cols + 1); //create memory for (row * col) elements
}
void freeMemoryInt(int rows)
{
int i;
for(i=0;i<rows; i++)
if(array[i]) free(array[i]);//call free for each row
free(array); //free pointer array(will clean up everything allocated)
}

Related

Why am i getting error in function addRandomNumbers?

I am getting an error in addRandomNumbers(). Maybe I didn't correctly allocate memory dynamically? I really have no idea what I did wrong.
The error is:
'Exception thrown: read access violation. _array was 0x1110112.'
Here is my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void allocateArray(int** _array, int row, int col) {
_array = (int**)malloc(sizeof(int*) * row);
for (int i = 0; i < row; i++)
_array[i] = (int*)malloc(sizeof(int) * col);
}
void addRandomNumbers(int** _array, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
_array[i][j] = rand() % 10;
}
}
}
void print(int** _array, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", _array[i][j]);
}
printf("\n");
}
}
int main() {
srand((unsigned)time(NULL));
int** _array = NULL;
allocateArray(_array, 5, 5);
addRandomNumbers(_array, 5, 5);
print(_array, 5, 5);
return 0;
}
You're passing _array to the allocateArray function by value, so any changes to the corresponding parameter aren't reflected in the variable in the main function. This means that _array is still NULL when you pass it to addRandomNumbers.
Change allocateArray to return the allocated pointer:
int **allocateArray(int row, int col) {
int **_array = malloc(sizeof(int*) * row);
for (int i = 0; i < row; i++) {
_array[i] = malloc(sizeof(int) * col);
}
return _array;
}
Then assign the return value back to _array:
_array = allocateArray(5, 5);
Alternately, you can change the parameter type to int *** and dereference when using it:
void allocateArray(int ***_array, int row, int col) {
*_array = malloc(sizeof(int*) * row);
for (int i = 0; i < row; i++) {
(*_array)[i] = malloc(sizeof(int) * col);
}
}
And pass the address of the variable in main:
allocateArray(&_array, 5, 5);
I'm assuming you're running into a segmentation fault because that's the error I receive on my machine by running this code.
I think the issue is with allocateArray(), not addRandomNumbers(). addRandomNumbers() is unable to write to the array because the array was not allocated properly. Try this instead:
void allocateArray(int ***_array, int row, int col) {
*_array = (int **)malloc(row * sizeof(int *));
for (int i = 0; i < row; ++i) {
(*_array)[i] = (int *)malloc(col * sizeof(int));
}
}
Likewise, to free the memory, try:
void freeArray(int **_array, int row) {
for (int i = 0; i < row; ++i) {
free(arr[row]);
}
free(arr);
}

CodeSignal problem. I want to complete the code

I have the following problem. The function printMatrix
Receive an matrix for example:
matrix:
[[0,1,1,2],
[0,5,0,0],
[2,0,3,3]]
The code that I must use is the following:
// Definition for arrays:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
void printMatrix(arr_arr_integer matrix)
{
}
As a clue they give me that the number of columns and rows can be determined in the following way.
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
//Or
int columns = matrix.arr[0].size; //No.columns
int rows = matrix.size; //No.rows
My question lies in how is the rest of the code written so that the previous tracks can work?
That is, for this to work within the function printMatrix
What should you add or modify in your code for the above methods to work?
typedef struct arr_arr_integer {
int size;
type *arr;
} arr_arr_integer;
arr_arr_integer alloc_arr_arr_integer(int len) {
arr_arr_integer a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
return a;
}
void printMatrix(arr_arr_integer matrix)
{
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
//print matrix?
}
int main(int argc, char const *argv[])
{
//input matrix?
printMatrix(arr_arr_integer matrix)
return 0;
}
I repeat. I must use this code strictly
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
The problem is that when I try to use those tracks I get the following compilation error.
error: request for member 'size' in something not a structure or union
The function alloc_arr_integer allocates a 1D array of integers.
If you need a 2D array, you'll have to call the function multiple times.
Something like:
arr_integer my2Darray[rows];
// Create the 2D array
for (int i = 0; i < rows; ++i)
{
my2Darray[i] = alloc_arr_integer(columns);
assert(my2Darray[i].arr != NULL);
}
// Initialize the 2D array
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
my2Darray[i].arr[j] = i * 1000 + j;
}
}
Putting it together:
int main(void)
{
int rows = 3;
int columns = 5;
arr_integer my2Darray[rows];
// Create the 2D array
for (int i = 0; i < rows; ++i)
{
my2Darray[i] = alloc_arr_integer(columns);
assert(my2Darray[i].arr != NULL);
}
//Initialize the 2D array
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
my2Darray[i].arr[j] = (i + 1) * 1000 + j;
}
}
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
printf("%d ", my2Darray[i].arr[j]);
}
printf("\n");
}
return 0;
}
OUTPUT
1000 1001 1002 1003 1004
2000 2001 2002 2003 2004
3000 3001 3002 3003 3004
I assume memory allocation for 'matrix' is done somewhere else.
void printMatrix(arr_arr_integer matrix)
{
int rows = matrix.size;
int columns = matrix.arr.size;
int i, j = 0;
/*print array*/
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
printf("%d ", a.arr[i].arr[j]);
printf("\n");
}
}
I was practicing for code signal and I wrote my own functions to stablish the arrays. They are as shown below (even though this is a little bit too late maybe).
typedef struct arr_integer
{
int size;
int *arr;
} arr_integer;
typedef struct arr_arr_integer
{
int size;
arr_integer *arr;
} arr_arr_integer;
arr_integer alloc_arr_integer(int size)
{
arr_integer *pointer;
pointer = malloc(sizeof(arr_integer));
pointer->size = size;
pointer->arr = malloc(size * sizeof(int));
return *pointer;
}
arr_arr_integer alloc_arr_arr_integer(int size)
{
arr_arr_integer *pointer;
pointer = malloc(sizeof(arr_arr_integer));
pointer->size = size;
pointer->arr = malloc(size * sizeof(arr_integer));
for (int i = 0; i < size; i++)
{
pointer->arr[i].arr = malloc(size * sizeof(int));
}
return *pointer;
}

seg fault when I try to create a 2d array of structs

Why would I be getting a seg fault at the highlighted line. Am I accessing the 2d array wrong? tempMap is a 1d array with all the values for the 2d array, for example [0,1,0,0,0,0,1,0] and since I know the number of rows and columns I am trying to make it into a 2d array of Spaces (which is my struct). Any help is very much appreciated.
int opt;
char *filename = NULL;
Space **map;
char *tempMap;
if (i != 0){
int col = getCol(filename);
int row = getRow(filename, col);
printf("%d x %d\n", row, col);
map = create_map(row, col, filename);
tempMap = populate_map(map, filename);
int curIndx=0;
for (int l = 0; l < 100; ++l) {
printf("%c", tempMap[l]);
}
for (int j = 0; j < row; ++j) {
for (int k = 0; k < col; ++k) {
map[j][k] = makeNewSpace(tempMap[curIndx],row,col); //<-----------This Line
curIndx++;
}
}
}
Also here is the makeNewSpace()
Space makeNewSpace(char character, int row, int column){
Space space;
space.character = character;
space.isVisited = false;
space.row= row;
space.column = column;
return space;
}
And this is where I allocate space for the 2d array.
Space **create_map( int row, int col, char *fileName) {
Space *values = calloc(row * col, 2* sizeof(char) + (4 * sizeof(int)));
Space **map = malloc(row * sizeof(char *));
for (int i = 0; i < row; ++i) {
map[i] = values + i * col;
}
return map;
}
Lastly here is my struct
typedef struct Space{
char character;
bool isVisited;
int row;
int column;
}Space;
Not sure if this is what you're going for, a dynamically allocated 2d array of Space structs.
#include <stdio.h>
#include <stdlib.h>
// Space struct definition
typedef struct {
int data;
} Space;
int main() {
int i;
// Allocate memory for the rows
Space** space2d = malloc(sizeof(Space*) * 3);
// Allocate memory for the columns
for(i = 0; i < 3; ++i) {
space2d[i] = malloc(sizeof(Space) * 5);
}
// Example setting one of the struct's members inside the 2d array
space2d[0][0].data = 100;
printf("%d\n", space2d[0][0].data);
// Freeing the 2d array
for(i = 0; i < 3; ++i)
free(space2d[i]);
free(space2d);
}

Passing array of pointers as argument to function in C

I've written a piece of code but I'm not sure about how it works.
I want to create an array of pointers and pass it as argument to a function, like the following:
int main()
{
int *array[10] = {0};
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int *));
}
testFunction(array);
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
return 0;
}
void testFunction(int *array[3])
{
//do something
return;
}
What I don't understand is the following. I declare array as an array of pointers, allocate memory to it by using malloc and then proceed to call testFunction. I want to pass the array by reference, and I understand that when I call the function by using testFunction(array), the array decays to a pointer to its first element (which will be a pointer also). But why in the parameters list I have to write (int *array[3]) with * and not just (int array[3])?
A parameter of type * can accept an argument of type [], but not anything in type.
If you write void testFunction(int arg[3]) it's fine, but you won't be able to access array[1] and array[2] and so on, only the first 3 elements of where array[0] points to. Also a comversion is required (call with testFunction((int*)array);.
As a good practice, it's necessary to make the function parametera consistent with what's passed as arguments. So int *array[10] can be passed to f(int **arg) or f(int *arg[]), but neither f(int *arg) nor f(int arg[]).
void testFunction(int **array, int int_arr_size, int size_of_array_of_pointers)
{
for(int j = 0; j < size_of_array_of_pointers; j++)
{
int *arrptr = array[j]; // this pointer only to understand the idea.
for(int i = 0; i < int_arr_size; i++)
{
arrptr[i] = i + 1;
}
}
}
and
int main()
{
int *array[10];
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
array[i] = malloc(3*sizeof(int));
}
testFunction(array, 3, sizeof(array) / sizeof(int *));
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
free(array[i]);
}
return 0;
}
Evering depends on what // do something means in your case.
Let's start from simple : perhaps, you need just array of integers
If your function change only values in array but does not change size, you can pass it as int *array or int array[3].
int *array[3] allows to work only with arrays of size 3, but if you can works with any arrays of int option int *array require additional argument int size:
void testFunction(int *array, int arr_size)
{
int i;
for(i = 0; i < arr_size; i++)
{
array[i] = i + 1;
}
return;
}
Next : if array of pointers are needed
Argument should be int *array[3] or better int **array (pointer to pointer).
Looking at the initialization loop (I changed sizeof(int *) to sizeof(int))
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
}
I suppose you need 2-dimension array, so you can pass int **array but with sizes of two dimensions or one size for case of square matrix (height equal to width):
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
for(row = 0; row < hSize; row++)
{
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}
And finally : memory allocation for 2D-array
Consider the following variant of your main:
int main()
{
int **array;
// allocate memory for 3 pointers int*
array = (int *)malloc(3*sizeof(int *));
if(array == NULL)
return 1; // stop the program
// then init these 3 pointers with addreses for 3 int
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
if(array[i] == NULL) return 1;
}
testFunction(array, 3, 3);
// First, free memory allocated for int
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
// then free memory allocated for pointers
free(array);
return 0;
}
Pay attention, that value returned by malloc should be checked before usage (NULL means memory was not allocated).
For the same reasons check can be added inside function:
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
if(array == NULL) // check here
return;
for(row = 0; row < hSize; row++)
{
if(array[row] == NULL) // and here
return;
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}

a value of type "void *" cannot be assigned to an entity of type "int **" last

I'm making a program which dynamically creating 2d array.but it's showing the error which I mentioned on the title. I'm using Visual Studio 2015.
// last.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include "stdlib.h"
double selectionSort(int * number, int number_count);
void print2d(int ** array, int rows, int cols);
void twodarray();
void main(int argc, char* argv[])
{
int num_count = 10000;
int num[10000];
for (int i = 0; i < num_count; i++)
{
num[i] = rand();
}
double sortTime = selectionSort(num, num_count);
printf("Total Runtime is: %.0f milliseconds. \n", sortTime * 1000);
twodarray();
getchar();
}
double selectionSort(int * number, int number_count)
{
clock_t start, end;
double duration;
int min;
start = clock();
for (int i = 0; i < number_count - 1; i++)
{
min = i;
for (int j = i + 1; j < number_count; j++)
{
if (number[min] > number[j])
{
min = j;
}
}
if (min != i)
{
int temp = number[min];
number[min] = number[i];
number[i] = temp;
}
}
end = clock();
return duration = (double)(end - start) / CLOCKS_PER_SEC;
}
void print2d(int ** array, int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0, j < cols; j++;)
{
printf("%10d ", array[i][j]);
}
puts("");
}
}
void twodarray()
{
int **twod;
int rows = 10;
twod = malloc(rows * sizeof(int));
int i,cols = 10;
for (i = 0; i < rows; i++)
{
twod[i] = malloc(cols*sizeof(int));
print2d(twod, rows, cols);
}
for (i = 0; rows; i++)
{
free(twod[i]);
free(twod);
}
}
In c++ you need to cast when assigining a void * pointer to another type of pointer. But in c++ you should not use malloc(), instead use
int **twod = new int *[rows];
If you didn't mean to write a c++ program, rename the file. Change the extension from .cpp to .c.
Your allocation is wrong too, as pointed out by #KeineLust here.
This is wrong:
int **twod;
int rows = 10;
twod = malloc(rows * sizeof(int));
You need to reserve space for n pointers to int, not for n ints, change to
twod = malloc(rows * sizeof(int *));
And here:
for (j = 0, j < cols; j++;)
^ ^
Use a semicolon instead of a comma and also remove the last semicolon.
Another problem:
for (i = 0; rows; i++)
{
free(twod[i]);
free(twod); /* Don't free twod in the loop, one malloc -> one free */
}
And as pointed out by Nicat and Iharob, it seems that you are mixing C and C++, use the proper extension (.c)

Resources