Segmentation Fault upon pointer dereferencing order - c

I'm trying to read a Matrix as here:
I've tried it on Cygwin, and MinGW compilers.
#include <stdio.h>
#include <stdlib.h>
typedef struct _Matrix {
int **data;
int m;
int n;
} Matrix;
Matrix *read_matrix(void) {
Matrix *A;
int i, j;
int **ptr;
A = (Matrix *) malloc(sizeof(Matrix));
if(A == NULL) {
return NULL;
}
printf("Enter m : ");
scanf("%d", &A->m);
printf("Enter n : ");
scanf("%d", &A->n);
ptr = (int **) malloc(A->m * A->n * sizeof(int));
/*-- >> A->data = ptr; << --*/
if(A->data == NULL) {
return NULL;
}
printf("\n");
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("Enter element [%d][%d] : ", i, j);
scanf("%d", &ptr[i][j]);
}
}
A->data = ptr;
return A;
}
int main() {
Matrix *A;
A = read_matrix();
free(A->data); /* A-- A->data is NULL --*/
free(A);
return 0;
}
If I set A->data before reading in values, I get a SEGMENTATION FAULT.
However, the code here does not appear to crash. However A->data returns NULL. What am I missing here?

A single pointer is all that is needed for the allocation being used.
#include <stdio.h>
#include <stdlib.h>
typedef struct _Matrix {
int *data; //single pointer
int m;
int n;
} Matrix;
Matrix *read_matrix(void) {
Matrix *A;
int i, j;
A = malloc(sizeof(Matrix));
if(A == NULL) {
return NULL;
}
printf("Enter m : ");
scanf("%d", &A->m);
printf("Enter n : ");
scanf("%d", &A->n);
A->data = malloc(A->m * A->n * sizeof(int));
if(A->data == NULL) {
return A;
}
printf("\n");
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("Enter element [%d][%d] : ", i, j);
scanf("%d", &A->data[( j * A->m) + i]);
}
}
return A;
}
int main() {
Matrix *A;
int i;
int j;
A = read_matrix();
if ( A) {
if ( A->data) {
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("A[%d][%d]= %d\n", i, j, A->data[( j * A->m) + i]);
}
}
free(A->data);
}
free(A);
}
return 0;
}

Related

inserting values to an array of pointers to linked lists, the array is in a struct | C

i have been trying to figure out the problem for 7-8h,
the thing that i must build a matrix multiplication func, using a given structs and an array of pointers to linked lists(The Matrix)
everything must be allocated by malloc,
Here is the given structs:
typedef struct cellNode
{
int cell;
struct cellNode* next;
} Node;
typedef struct matrix
{
int numRows;
int numColumns;
Node** rows;
} Matrix;
and here is the function to build the matrix and to allocate it:
Matrix* MatrixBuilder(Matrix* A, int rows, int cols)
{
int i=0;
A->numColumns=cols;
A->numRows=rows;
A->rows = (Node**)malloc(rows * sizeof(Node*));
if (A->rows == NULL)
{
printf("memory error!");
exit(1);
}
for (i=0; i<rows; i++)
{
A->rows[i] = (Node*)malloc(rows * sizeof(Node));
if (A->rows[i] == NULL)
{
printf("memory error!");
exit(1);
}
}
for (i=0; i<rows; i++)
{
A->rows[i] = NULL;
}
return A;
}
and here is the function to build the node, with a given data and link it to the list:
Matrix* MatrixBuilder(Matrix* A, int rows, int cols)
{
int i=0;
A->numColumns=cols;
A->numRows=rows;
A->rows = (Node**)malloc(rows * sizeof(Node*));
if (A->rows == NULL)
{
printf("memory error!");
exit(1);
}
for (i=0; i<rows; i++)
{
A->rows[i] = (Node*)malloc(rows * sizeof(Node));
if (A->rows[i] == NULL)
{
printf("memory error!");
exit(1);
}
}
for (i=0; i<rows; i++)
{
A->rows[i] = NULL;
}
return A;
}
and this is my main function:
int main()
{
int n,m,k,i,x,j=0; /* x to help me insert integers into the list */
Matrix* A = (Matrix*)malloc(sizeof(Matrix));
Matrix* B = (Matrix*)malloc(sizeof(Matrix));
Matrix* C = (Matrix*)malloc(sizeof(Matrix));
printf("please enter n:");
scanf("%d",&n);
printf("please enter m:");
scanf("%d",&m);
printf("please enter k:");
scanf("%d",&k);
A = MatrixBuilder(A, n, m);
B = MatrixBuilder(B, m, k);
C = MatrixBuilder(C, n, k);
for (i=0; i<n; i++)
{
printf("Enter row %d data\n",i);
for (j=0; j<m; j++)
{
scanf("%d", &x);
NodeBuilder_Insert(A->rows[j], x);
}
}
return 0;
}
when i run it, it stops right when i enter the first element in first row, so i quess the problem is in the NodeBuilder function, but i cant find it,
and i am not sure if i allocated everything properly...

do we need the original pointer to free up memory the memory in c?

will this cleanProgram() function free up all the memory allocated by malloc() in createArray() function in the below code.
#include <stdio.h>
#include <stdlib.h>
typedef struct S_Array
{
int *arr;
int size;
}Array;
Array* createArray()
{
Array* a = (Array*)malloc(sizeof(Array));
printf("enter the size of array: ");
scanf("%d",&a->size);
a->arr = (int*)malloc(a->size*sizeof(int));
printf("enter the array elements: ");
for(int i=0; i<a->size; i++) {
scanf("%d",&a->arr[i]);
}
return a;
}
void cleanProgram(Array *a){
free(a->arr);
free(a);
}
void traverse(Array *a){
for(int i=0; i<a->size; i++){
printf("%d ",a->arr[i]);
}
}
int main()
{
Array* a = createArray();
traverse(a);
cleanProgram(a);
return 0;
}
You are freeing memory correctly, but you're not checking for allocation errors, and therefore you also have a memory leak in createArray():
#include <stdio.h>
#include <stdlib.h>
typedef struct S_Array {
int* arr;
int size;
} Array;
Array* createArray(void) {
Array* a = malloc(sizeof(Array));
// let's check for errors
if (a == NULL) {
return NULL;
}
printf("enter the size of array: ");
scanf("%d", &a->size); // let's assume input is always correct
a->arr = malloc(a->size * sizeof(int));
// let's check for errors
if (a->arr == NULL) {
free(a); // here we avoid memory leaks
return NULL;
}
for (int i = 0; i < a->size; i++) {
printf("enter element arr[%d]: ", i); // clearer message
scanf("%d", &a->arr[i]); // let's assume input is always correct
}
return a;
}
void cleanProgram(Array* a) {
free(a->arr);
free(a);
}
void traverse(Array* a) {
for (int i = 0; i < a->size; i++) {
printf("%d ", a->arr[i]);
}
printf("\n");
}
int main(void) {
Array* a = createArray();
// let's check for errors
if (a == NULL) {
printf("ERROR: cannot create array\n");
return 1;
}
traverse(a);
cleanProgram(a);
return 0;
}

Why am I getting segmentation fault and how do I solve this?

C program for bubble sort using a minimum of 4 functions.(input,output,compute,main)
No global variables allowed.
No printf or scanf in compute.
No printf or scanf in main
Input should not call compute.
compute should not call output.
I haven't really understood pointers and functions.
#include <stdio.h>
void input(int* size, int* arr[])
{
printf("Enter the size of the array: ");
scanf("%d",size);
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d", arr[i]);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int arr[100],int size)
{
for(int i = 0;i < size - 1;i++)
{
for(int j = 0;j < size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int size,int* arr)
{
printf("Sorted array\n");
for(int i = 0;i < size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int* input_values[50];
int size;
input(&size, input_values);
bubble_sort(size,*input_values);
output(size, *input_values);
return 0;
}
No errors but showing segmentation fault.How do I solve this?
So your problem is here :
scanf(" %d", arr[i]);
You have to change this to :
scanf(" %d", &arr[i]);
This is the main problem, but there are a lot of others.
Also you have to change the order of parameters in
bubble_sort(size,*input_values);
to
bubble_sort(input_values,size);
and
output(size, *input_values);
to
output(size, input_values);
Also in order this to work at all i have changed the
scanf("%d", &arr[i]);
to
scanf(" %d", &arr[i]);
Actually your code is full of mistakes like the usage of scanf and the usage of pointers and arrays, the following is a workable version of you code see and compare:
#include <stdio.h>
void input(int* size, int arr[])
{
char chr;
printf("Enter the size of the array: ");
scanf( "%d%c", size, &chr );
printf("Enter the elements of the array\n");
for(int i = 0;i < *size; i++)
{
scanf("%d%c", &arr[i], &chr);
}
}
void swap(int *x,int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubble_sort(int* size,int arr[])
{
for(int i = 0;i < *size - 1;i++)
{
for(int j = 0;j < *size - 1 - i;j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}
void output(int* size,int arr[])
{
printf("Sorted array\n");
for(int i = 0;i < *size;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int input_values[50];
int s = 0;
int* size = &s;
input(size, input_values);
bubble_sort(size,input_values);
output(size, input_values);
return 0;
}

I want that vector_total dont have any repeated number

I need that vector_total dont have any repeated number.
Function for entry vector1 and vector2 that are declared in main().
void entrada_vectors(int vector1[], int vector2[], int vector_total[], int *n, int *m)
{
int i=0, j=0;
/*Entrarem els nombres del vector 1 primer */
for (i=0; i<*n; i++)
{
vector_total[i]=vector1[i];
}
/*Entrarem els nombres del vector 2 després */
for (i=*n; i<*n+*m; i++)
{
if (j<*m)
{
vector_total[i]=vector2[j];
j++;
}
}
}
Function 2. This is for order numbers in vector_total.
void ordena(int vector_total[], int *n, int *m)
{
int i=0, j=0;
int aux=0;
for (i=0; i<*n+*m-1; i++)
{
for (j=0; j<*n+*m-1; j++)
{
if (vector_total[j]>vector_total[j+1])
{
aux=vector_total[j];
vector_total[j]=vector_total[j+1];
vector_total[j+1]=aux;
aux=0;
}
}
}
}
Function 3. Print vector_total
void mostra(int vector_total[], int *n, int *m )
{ int i;
for (i=0; i<*n+*m; i++)
{
printf ("Pos %d del vector: %d\n", i, vector_total[i] );
}
}
Function 4. Here are the problem!! This function is for clean my vector_total and drop the repeated numbers.
void limpiar_repetidos(int vector_total[], int *n, int *m)
{
int x=0, i=0, j=0;
for (i=0; i<*n+*m-1; i++)
{
for (j=0; j<*n+*m-1; j++)
{
if (vector_total[j]==vector_total[j+1])
{
x=j+1;
for (i=*n+*m; i>x; i--)
{
vector_total[i-1]=vector_total[i];
}
}
}
}
}
And here is my main. And my declaration variables:
int vector1[]={7,1,5,3,4,2};
int vector2[]={3,7,3,0,9,10};
int n=sizeof(vector1)/sizeof(vector1[0]);
int m=sizeof(vector2)/sizeof(vector2[0]);
int vector_total[n+m];
main()
{
entrada_vectors(vector1, vector2, vector_total, &n, &m);
ordena(vector_total, &n, &m);
mostra(vector_total, &n, &m);
limpiar_repetidos(vector_total, &n, &m);
printf ("==================\n");
mostra(vector_total, &n, &m);
return 0;
}
Thanks everybody! :)
1) If function deal with only a vector_total , Length of the vector_total is better to pass by one argument. Also you do not need to pointer pass if it will not change.
void mostra(int vector_total[], int len){
int i;
for (i=0; i<len; i++) {
printf ("Pos %d del vector: %d\n", i, vector_total[i] );
}
}
2) function need a new length after the element has been removed. Also, deletion of adjacent same elements that can be like this.
int limpiar_repetidos(int vector_total[], int len){//int *n, int *m --> int len
int i, size, new_size;
size = len;
for(i = new_size = 1; i < size; ++i){
if(vector_total[new_size-1] != vector_total[i])
vector_total[new_size++] = vector_total[i];
}
return new_size;
}
Example of use
mostra(vector_total, m + n);
int l = limpiar_repetidos(vector_total, n + m);
mostra(vector_total, l);

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).

Resources