I'm trying to free a jagged array after making it, but I am encountering an issue with a segmentation fault as I try to delete it:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *col;
int **row;
//Declare and fill col array
col = malloc(argc * sizeof (int));
for (int k = 1; k < argc; k++) {
col[k] = atoi(argv[k]);
}
row = malloc(argc * sizeof (int*));
//build the ragged array
for (int i = 0; i < argc; i++) {
row[i] = malloc(sizeof (int) * col[i]);
for (int j = 0; j < col[i]; j++) {
row[i][j] = 1;
}
}
//trying to delete it but its not working
for (int i = 0; i < argc; i++) {
for (int j = 0; j < col[i]; j++) {
int* currentIntPtr = row[i];
free(currentIntPtr);
}
}
free(row);
return 0;
}
Compiler message:
Segmentation fault (core dumped)
row = malloc(argc * sizeof (int));
This should be changed to:
row = malloc(argc * sizeof (int *));
As you are allocating a new integer array for each element in "row" and therefore, each element in "row" must be an integer pointer so that it holds the address which points to an array of integers.
Moreover, you are freeing memory in a wrong way.
for (int i = 0; i < argc; i++) {
for (int j = 0; j < col[i]; j++) {
int* currentIntPtr = row[i][j];
free(currentIntPtr);
}
}
This piece of code won't work:.
int* currentIntPtr = row[i][j];
the type of row[i][j] is integer type and you are and you are assigning it to an integer pointer. What this will do is rather than freeing row[i][j] it will take the value of row[i][j] try to free that address which may be out of address space of the program and hence is not allowed and hence the segmentation fault.
The appropriate which would work will be:
for (int i = 0; i < argc; i++) {
int* currentIntPtr = row[i];
free(currentIntPtr);
}