Segmentation Fault:11 Error messages in C Terminal - c

While compiling in the terminal I keep getting the error Segmentation Fault: 11. The goal is to make dark circles on a picture of a boarder, ect with command. My reasoning that it isn't working if because of my File IO. I did it without the in & out FILE types and changed the two functions that are called in pgmUtility to not call in files and the program ran smoothly. So I'm assuming I need to have help focusing on the issues I have with my file IO.
Command used:
$ ./a.out -c 470 355 100 < balloons.ascii.pgm > TestImages/balloons_c100_4.pgm
It uses main.c program that relates to pgmUtility.c
This is Main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "pgmUtility.h"
#define ROWS 4
#define COLS 100
void usage(void)
{
printf("Usage\n");
printf(" -h Help Dialog\n");
printf(" -e edgeWidth < OldImageFile > NewImageFile\n");
printf(" -c centerRow centerCol radius < OldImageFile > NewImageFile\n");
printf(" -e edgeWidth -c radius centerRow centerCol < OldImageFile > NewImageFile\n");
exit (8);
}
int main(int argc, char * argv[]) {
FILE *fp;
FILE *out;
int i, j;
int flag1 = 0; //-e switch (edge draw)
int flag2 = 0; //-c switch (circle draw)
int numRows, numCols, centerRow, centerCol, radius, edgeWidth;
char originalImage[100], newImageFile[100];
char **header = (char**) malloc (sizeof(char*)*4);
int **pixels;
//command line argument parsing
//turn flag switches on or off
if(argc < 3)
usage();
if(argc > 7)
usage();
for(i = 1; i < argc; i++) {
if(strncmp(argv[i], "-e", 2) == 0) {
//set flag on
//get edge with values)
if(atoi(argv[i+1]) == 0) {
usage();
}
edgeWidth = atoi(argv[i+1]);
if(argv[i+2] != NULL) {
if(atoi(argv[i+2]) != 0) {
usage();
}
}
flag1 = 1;
}
if(strncmp(argv[i], "-c", 2) == 0) {
//set flag on
//get radius and center values
if(atoi(argv[i+1]) == 0) {
usage();
}
centerRow = atoi(argv[i+1]);
centerCol = atoi(argv[i+2]);
radius = atoi(argv[i+3]);
flag2 = 1;
strcpy(originalImage, argv[5]);
strcpy(newImageFile, argv[6]);
fp = fopen(originalImage, "r");
out = fopen(newImageFile, "w");
}
if(strncmp(argv[i], "-h", 2) == 0) {
usage();
}
}
//allocate memory for header array
header = (char **)malloc(ROWS * sizeof(char));
for(i = 0; i < ROWS; i++) {
for(j = 0; j < COLS; j++) {
header[i] = (char *)malloc(COLS * sizeof(char *));
}
}
//read pgm file
pixels = pgmRead(header, &numRows, &numCols, fp);
if(pixels == NULL)
usage();
switch(flag1) {
case 1 :
if(flag2 == 1) {
//execute circle draw and edge draw
pgmDrawCircle(pixels, numRows, numCols, centerRow, centerCol, radius, header);
pgmDrawEdge(pixels, numRows, numCols, edgeWidth, header);
}
else {
//execute only edge draw only
pgmDrawEdge(pixels, numRows, numCols, edgeWidth, header);
}
break;
case 0 :
if(flag2 == 1) {
//execute circle draw
pgmDrawCircle(pixels, numRows, numCols, centerRow, centerCol, radius, header);
}
break;
default :
usage();
break;
}
//write new pgm file
pgmWrite((const char **)header, (const int **)pixels, numRows, numCols, out);
//Garbage Collection
//Fix this
//free(pixels);
//free(header);
for(i = 0; i < numRows; i++) {
int *current= pixels[i];
free(current);
}
for(i = 0; i < ROWS; i++) {
char *current = header[i];
free(current);
}
return 0;
}
This is two functions from pgmUtility.c that I think may be the cause of the issue.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "pgmUtility.h"
#define ROWS 4
#define COLS 100
// Implement or define each function prototypes listed in pgmUtility.h file.
// NOTE: You can NOT change the input, output, and argument type of the functions in pgmUtility.h
// NOTE: You can NOT change the prototype (signature) of any functions listed in pgmUtility.h
int ** pgmRead( char **header, int *numRows, int *numCols, FILE *in ){
int r, c;
int **array;
for(r = 0; r < ROWS; r++) {
fgets(header[r], COLS, stdin);
if(header == NULL)
return NULL;
}
//sscanf parses the numRows and numCols
sscanf(header[ROWS - 2], "%d %d", numCols, numRows);
//read in pixel map
array = (int **)malloc(*numRows * sizeof(int *));
for(r = 0; r < *numRows; r++) {
array[r] = (int *)malloc(*numCols * sizeof(int));
}
for(r = 0; r < *numRows; r++) {
for(c = 0; c < *numCols; c++) {
fscanf(in, "%d", *(array + r) + c );
}
}
fclose(in);
return array;
}
int pgmWrite( const char **header, const int **pixels, int numRows, int numCols, FILE *out ){
//iterate straight through pixels
//setup with a loop to insert a new line every "numCols" and keep printing until "numRows + 1" is reached (as soon as numRows + 1 break loop)
int i, j;
for(i = 0; i < 4; i++){
//printf("%s", *header[i]);
fprintf(out, "%c", *header[i]);
}
//for(i = 0; i < 4; i++)
//fprintf(out, "*I=%d**%s**", i, header[i]);
for(j = 0; j < numRows; j++){
for(i = 0; i < numCols; i++)
fprintf(out, "%d ", pixels[i][j]);
fprintf(out, "\n");
}
fclose(out);
return 0;
}

You're not allocating the header arrays correctly. It should be:
header = malloc(ROWS * sizeof(char*));
for(i = 0; i < ROWS; i++) {
header[i] = malloc(COLS * sizeof(char));
}
You had the wrong types in the two sizeof calls.
You didn't need the inner j loop at all, you were repeatedly assigning to the same header[i].
And for C (but not C++) see: Do I cast the result of malloc?
Also, at the beginning of main() you have an extra allocation that you never use or free:
char **header = (char**) malloc (sizeof(char*)*4);
You should get rid of this.
It's not related to the error, but this is wrong:
if(header == NULL)
return NULL;
You should be testing header[r].
For clarity, I recommend rewriting:
fscanf(in, "%d", *(array + r) + c );
as:
fscanf(in, "%d", &array[r][c]);

It appears (even after correcting the malloc call as correctly suggested), you are allocating header[i] COLS number of times.
header = malloc(ROWS * sizeof(char*));
for(i = 0; i < ROWS; i++) {
for(j = 0; j < COLS; j++) {
header[i] = malloc(COLS * sizeof(char)); // this happens COLS times
}
}
That will leave COLS number of each header[i] allocated. As I read your code, you need only allocate a single char array for each header[i]. To do this, you need to move header[i] = malloc(COLS * sizeof(char)); outside the for(j = 0; j < COLS; j++) loop:
header = malloc(ROWS * sizeof(char*));
for(i = 0; i < ROWS; i++) {
header[i] = malloc(COLS * sizeof(char));
}
You should also validate that header and each header[i] were successfully allocated.

Related

Segmentation Fault Issue in Matrix GDB Project

I'm working on a GDB project for class an I'm finding issues with a segfault portion in a piece of code that reads a file and creates a matrix with the input. GDB brings me to the "printf("%.2d\t", mat[row][col]);" in printMatrix() but I can't seem to grasp what exactly goes wrong.
int main(int argc, char* argv[])
{
FILE* fp = fopen(argv[1], "r");
int size = 0;
int **mat = readFile(fp, &size);
printMatrix(mat, size);
return 0;
}
int** readFile(FILE* fp, int *size)
{
fscanf(fp, "%d", size);
int num = *size;
int index = 0;
int** mat = (int**)malloc(num * sizeof(int));
for(index = 0; index < num; index++)
mat[index] = (int*)malloc(num * sizeof(int));
int row = 0;
int col = 0;
for(; row < num; row++)
{
for(; col < num; col++)
{
fscanf(fp, "%d", &mat[row][col]);
}
}
return mat;
}
void printMatrix (int** mat, int num)
{
int row = 0;
int col = 0;
for(row = 0; row < num; row++)
{
for(col = 0; col < num; col++)
{
printf("%.2d\t", mat[row][col]); /* gdb indicates segfault here */
}
printf("\n");
}
}
I tried tinkering with the for loop but can't seem to get the expected output.
int** mat = (int**)malloc(num * sizeof(int));
It should be
int** mat = malloc(num * sizeof(int *));
or better
int** mat = malloc(num * sizeof(*mat));
Also use site_t for sizes not int.
I personally would use pointer to array not array of pointers to remove one level of indirection (difficult (de)/allocation , performance penalty)
Always check the result of malloc and scanf
void *readFile(FILE* fp, size_t *size)
{
if(fscanf(fp, "%d", size) != 1) { /* handle error */}
int (*mat)[*size] = malloc(*size * sizeof(*mat));
if(mat)
{
for(size_t row = 0; row < *size; row++)
{
for(size_t col = 0; col < *size; col++)
{
if(fscanf(fp, "%d", &mat[row][col]) != 1) { /* handle error */}
}
}
}
return mat;
}
void printMatrix (size_t num, int (*mat)[num])
{
if(mat)
{
for(size_t row = 0; row < num; row++)
{
for(size_t col = 0; col < num; col++)
{
printf("%.2d\t", mat[row][col]); /* gdb indicates segfault here */
}
printf("\n");
}
}
}

Dynamically allocate 2D char array, and create a copy of itself

I have to dynamically allocate a 2d char array where the number of columns and lines are given by the user. After that, I need to create a copy of that 2d char array so I can manipulate its data.
This is how I tried it. When I try to print the copy array, it prints ok, but it gives me a Segmentation fault (core dumped) error. Not sure what I have to do here.
char **original;
original = malloc(sizeof(char *) * lines);
int i, j;
for (i = 0; i < columns; i++)
{
original[i] = malloc(sizeof(char) * columns+ 1);
}
for (i = 0; i < lines; i++)
{
for (j = 0; j < columns; j++)
{
scanf(" %c", &original[i][j]);
}
}
//The following happens inside a different function. The original matrix was passed as a parameter.
char **copy = NULL ;
for (i = 0; i < lines; i++)
{
copy[i] = malloc(sizeof(char) * columns+ 1);
}
for (i = 0; i < lines; i++)
{
strcpy(copy[i],original[i]);
}
The first for is not correct you should do it on lines not column.
You can also copy with memcpy. or copy char by char.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char **original;
int lines = 3;
int columns = 2;
original = malloc(sizeof(char *) * lines);
int i, j;
for (i = 0; i < lines; i++)
{
original[i] = malloc(sizeof(char) * columns);
}
for (i = 0; i < lines; i++)
{
for (j = 0; j < columns; j++)
{
scanf(" %c", &original[i][j]);
}
}
//The following happens inside a different function. The original matriz was passed as a parameter.
char **copy = malloc(sizeof(char *) * lines);
for (i = 0; i < lines; i++)
{
copy[i] = malloc(sizeof(char) * columns);
}
for (i = 0; i < lines; i++)
{
for (j = 0; j < columns; j++) {
copy[i][j] = original[i][j];
}
}
return 0;
}

C program store file to jagged array and sort it

I am trying to create C program to read a text file and sort it by ascending order. The example of text file is
2
3; 2, 5, 7
6; 4, 7, 8, 9, 5, 2
with the first line indicated the number of rows, the number after the ";" indicated elements each rows and elements separated by ",".
So my idea is to create a dynamic jagged array with rows as the first number, then point each row to the different array with element. Sort the pointer arrays first then sort elements of each arrays. This is what I have tried so far
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int SortLists();
int main ()
{
int i,j = 0;
char filename[10]; //name of the file
char line[100];
int rows = 3; //I have to initialized this to test my code first
int cols;
int **jaggedArr; //jagged array
jaggerArr = malloc (rows*sizeof(int*)) ;
printf("Enter the file name with .txt : ");
scanf("%s", filename);
FILE *filePtr = fopen(filename, "r");
int num;
if (filePtr != NULL)
{
while (fgets(line, sizeof(line), filePtr) != NULL) //read each line of the text
{
cols = atoi(strtok(line, ";")); //use strtk to break elements
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
jaggedArr[i][j] = atoi(strtok(line, ",")); //parse into the jagged array
}
}
}
fclose(filePtr);
}
}
int SortLists(int list[], int size) //sort method
{
int i,j,temp;
for (i = 0; i < size; ++i)
{
for (j = i + 1; j < size; ++j)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
As a beginner in C, I am not familiar with the idea of pointer, which a lot different with C#.
Sorry for my bad English as its not my first language. Thank you so much for helping me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define S_(x) #x
#define S(x) S_(x)
void SortLists(int list[], int size);
int main(void){
char filename[FILENAME_MAX+1];
char line[100];
int rows, cols;
printf("Enter the file name with .txt : ");
scanf("%" S(FILENAME_MAX) "[^\n]%*c", filename);
FILE *filePtr = fopen(filename, "r");
if(!filePtr)
return EXIT_FAILURE;
fscanf(filePtr, "%d ", &rows);
int **jaggedArr;
jaggedArr = malloc (rows * sizeof(int*));
int *sizeArr = malloc(rows * sizeof(int));
int r = 0, c;
while (fgets(line, sizeof(line), filePtr) != NULL){
sizeArr[r] = cols = atoi(strtok(line, ";"));
jaggedArr[r] = malloc(cols * sizeof(int));
for (c = 0; c < cols; ++c){
jaggedArr[r][c] = atoi(strtok(NULL, ","));
}
SortLists(jaggedArr[r++], cols);
}
fclose(filePtr);
//check print and deallocation
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
free(jaggedArr[r]);
}
free(jaggedArr);
free(sizeArr);
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
for extra question.
#include <stdio.h>
void SortLists(int list[], int size);
void SortRows(int *jaggedArr[], int size, int *rowSize);
int main(void){
int row1[] = {4,7,8,9,5,2};
int row2[] = {2,5,7};
int *jaggedArr[] = { row1, row2};
int rows = 2;
int sizeArr[] = {6,3};
int i, r, c;
for(i=0;i<rows;++i)
SortLists(jaggedArr[i], sizeArr[i]);
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
printf("\n");
SortRows(jaggedArr, rows, sizeArr);
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void SortRows(int *jaggedArr[], int size, int *rowSize){
int i,j,temp,*tempp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (rowSize[i] > rowSize[j]){
//swap in pairs
temp = rowSize[i];
rowSize[i] = rowSize[j];
rowSize[j] = temp;
tempp = jaggedArr[i];
jaggedArr[i] = jaggedArr[j];
jaggedArr[j] = tempp;
}
}
}
}
#include <stdio.h>
void SortLists(int list[], int size);
void SortRows(int *jaggedArr[], int size);
int main(void){
int row1[] = {6, 4,7,8,9,5,2};//The first element represents the number of elements.
int row2[] = {3, 2,5,7};
int *jaggedArr[] = { row1, row2};
int rows = 2;
//int sizeArr[] = {6,3};//Not required
int i, r, c;
for(i=0;i<rows;++i)
SortLists(jaggedArr[i]+1, jaggedArr[i][0]);
SortRows(jaggedArr, rows);
for(r = 0;r < rows; ++r){
for(c = 1; c <= jaggedArr[r][0]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void SortRows(int *jaggedArr[], int size){
int i,j,*tempp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (jaggedArr[i][0] > jaggedArr[j][0]){
tempp = jaggedArr[i];
jaggedArr[i] = jaggedArr[j];
jaggedArr[j] = tempp;
}
}
}
}

Ansi C, Multithreading MatrixMultiplication

I have been programming this multiplethreaded matrix multiplication.
Somehow the programm works, but it does not give me the values of the result matrix.
Here it is the code:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int rowA, rowB, colA, colB;
int myNrThreads = 0;
double **matrixA, **matrixB, **matrixOut;
void *multiplyThread (void *param);
void fillAndCheckMatrice(double **matrix, FILE *myFile, int row, int column) {
char *line = NULL;
char *p;
ssize_t read;
int i = 0, j = 0;
size_t length = 0;
getline (&line, &length, myFile);
p = strtok(line, " ");
row = atoi(p);
p = strtok(NULL, " ");
column = atoi(p);
printf("%d, %d\n", row, column);
matrix = malloc(row * sizeof(double*));
for (j = 0; j < row; ++j) {
matrix[j] = malloc(column * sizeof(double));
}
i = 0;
while ((read = getline (&line, &length, myFile)) != -1) {
j = 0;
p = strtok(line, " ");
while (p != NULL) {
matrix[i][j] = atof(p);
++j;
p = strtok(NULL, " ");
}
++i;
}
free(line);
}
int main (int argc, char* argv[])
{
pthread_t *myThread;
int counter, j, r;
FILE *fileA = fopen("matrixA.txt", "r");
FILE *fileB = fopen ("matrixB.txt", "r");
if (argc!=2)
{
printf("Usage: %s number_of_threads\n",argv[0]);
exit(-1);
}
myNrThreads = (atoi)(argv[1]);
fillAndCheckMatrice(matrixA, fileA, rowA, colA);
fillAndCheckMatrice(matrixB, fileB, rowB, colB);
matrixOut = malloc(rowA * sizeof(double*));
for (counter = 0; counter < rowA; ++counter) {
matrixOut[counter] = malloc (colB * sizeof(double));
}
myThread = malloc(myNrThreads * sizeof(pthread_t));
for (counter = 1; counter < myNrThreads; ++counter) {
r = pthread_create (&myThread[counter], NULL, multiplyThread, (void*)counter);
if (r != 0 ) {
printf ("No threads create!");
free (myThread);
exit(-1);
}
}
multiplyThread(0);
for (counter = 1; counter < myNrThreads; ++counter) {
pthread_join(myThread[counter], NULL);
}
for (counter = 0; counter < rowA; ++counter) {
for (j = 0; j < colB; ++j) {
printf ("%.5f ", matrixOut[counter][j]);
}
printf("\n");
}
fclose(fileA);
fclose(fileB);
free(myThread);
free(matrixA);
free(matrixB);
free(matrixOut);
return 0;
}
/*
* The method gets on the first line the dimensions of the matrice.
* While filling every postion of our matrice, we control
* if the given dimensions are the real dimensions of the matrice.
* Everything is read from the .txt file, produced from our python
* generator.
*
*/
void *multiplyThread(void *param){
int myParam = (int)param;
int limitBegin = (myParam * rowA) / myNrThreads;
int limitEnd = ((myParam + 1) * rowA) / myNrThreads;
int counterI, counterJ, counterK;
for (counterI = limitBegin; counterI < rowA; ++counterI) {
for (counterJ = 0; counterJ < colB; ++counterJ) {
matrixOut[counterI][counterJ] = 0;
for (counterK = 0; counterK < rowB; ++counterK) {
matrixOut[counterI][counterJ] +=matrixA[counterI][counterK] * matrixB[counterK][counterJ];
}
}
}
printf("finished slice %d\n", myParam);
return 0;
}
Any idea why???
Thanx in advance.
PS: at the pthread_create I get a warning at (void*)counter btw
EDIT:
matrixA and matrixB are given through matrixA.txt and matrixB.txt. They are read and the values are taken from that.
One of the txt file would look like this:
2 2 // The dimensions of the matrice
12 14
13 15
EDIT3: The new one. Here I get segmentation fault 11:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
void *multiplyThread (void *param);
int rowA, rowB, colA, colB;
int myNrThreads = 0;
double **matrixA, **matrixB, **matrixOut;
void fillAndCheckMatrice(double **matrix, FILE *myFile, int ID) {
char *line = NULL;
char *p;
int row, column;
ssize_t read;
int i = 0, j = 0;
size_t length = 0;
getline (&line, &length, myFile);
p = strtok(line, " ");
row = atoi(p);
p = strtok(NULL, " ");
column = atoi(p);
printf("%d, %d\n", row, column);
if (ID == 1) {
rowA = row;
colA = column;
} else if (ID == 2) {
rowB = row;
colB = column;
}
matrix = malloc(row * sizeof(double*));
for (j = 0; j < row; ++j) {
matrix[j] = malloc(column * sizeof(double));
}
i = 0;
while ((read = getline (&line, &length, myFile)) != -1) {
j = 0;
p = strtok(line, " ");
while (p != NULL) {
matrix[i][j] = atof(p);
++j;
p = strtok(NULL, " ");
}
++i;
}
free(line);
}
int main (int argc, char* argv[])
{
pthread_t *myThread;
int counter, j, r;
FILE *fileA = fopen("matrixA.txt", "r");
FILE *fileB = fopen ("matrixB.txt", "r");
if (argc!=2)
{
printf("Usage: %s number_of_threads\n",argv[0]);
exit(-1);
}
myNrThreads = (atoi)(argv[1]);
fillAndCheckMatrice(matrixA, fileA, 1);
fillAndCheckMatrice(matrixB, fileB, 2);
matrixOut = malloc(rowA * sizeof(double*));
for (counter = 0; counter < rowA; ++counter) {
matrixOut[counter] = malloc (colB * sizeof(double));
}
for (counter = 0; counter < rowA; ++counter) {
for (j = 0; j < colB; ++j) {
printf ("%.5f ", matrixOut[counter][j]);
}
printf("\n");
}
myThread = malloc(myNrThreads * sizeof(pthread_t));
for (counter = 1; counter < myNrThreads; ++counter) {
printf("%d", counter);
if (pthread_create (&myThread[counter], NULL, multiplyThread, (void*)(intptr_t)counter) != 0) {
printf ("No threads create!");
free (myThread);
exit(-1);
}
}
for (counter = 0; counter < rowA; ++counter) {
for (j = 0; j < colB; ++j) {
printf ("%.5f ", matrixA[counter][j]);
}
printf("\n");
}
multiplyThread(0);
for (counter = 1; counter < myNrThreads; ++counter) {
pthread_join(myThread[counter], NULL);
}
fclose(fileA);
fclose(fileB);
free(myThread);
free(matrixA);
free(matrixB);
free(matrixOut);
return 0;
}
/*
* The method gets on the first line the dimensions of the matrice.
* While filling every postion of our matrice, we control
* if the given dimensions are the real dimensions of the matrice.
* Everything is read from the .txt file, produced from our python
* generator.
*
*/
void *multiplyThread(void *param){
int myParam = (int)param;
int limitBegin = (myParam * rowA) / myNrThreads;
int limitEnd = ((myParam + 1) * rowA) / myNrThreads;
int counterI, counterJ, counterK;
for (counterI = limitBegin; counterI < rowA; ++counterI) {
for (counterJ = 0; counterJ < colB; ++counterJ) {
matrixOut[counterI][counterJ] = 0;
for (counterK = 0; counterK < rowB; ++counterK) {
matrixOut[counterI][counterJ] +=matrixA[counterI][counterK] * matrixB[counterK][counterJ];
}
}
}
printf("finished slice %d\n", myParam);
return 0;
}
There are quite a few problems in the question code. Perhaps the best 'answer' would be to carefully walk through the code and point out some of the issues.
First, consider the following:
int rowA, rowB, colA, colB;
Nothing really wrong with the above line, until (later in main):
fillAndCheckMatrice(matrixA, fileA, rowA, colA);
fillAndCheckMatrice(matrixB, fileB, rowB, colB);
The above lines pass the 'values' of 'rowA', 'colA' 'rowB' and 'colB'. Being that these variables have no established values, it is obvious that there is trouble in the code.
Most likely, the intention is to initialize these values inside the 'fillAndCheckMatrice()' function. However, in order to initialize these variables, the 'address' of the variables must be passed into 'fillAndCheckMatrice()', (not their 'values'). Perhaps something like this:
fillAndCheckMatrice(matrixA, fileA, &rowA, &colA);
fillAndCheckMatrice(matrixB, fileB, &rowB, &colB);
Then, of course, the 'fillAndCheckMatrice()' will have to be modified as well; from:
void fillAndCheckMatrice(double **matrix, FILE *myFile, int row, int column) {
To:
void fillAndCheckMatrice(double **matrix, FILE *myFile, int *row, int *column) {
And then, of course, every reference to 'row' and 'column' will now have to deal with a pointer to a variable, instead of the variable value. Hence these:
row = atoi(p);
column = atoi(p);
printf("%d, %d\n", row, column);
Will have to change to these:
*row = atoi(p);
*column = atoi(p);
printf("%d, %d\n", *row, *column);
...and so forth...
matrix = malloc((*row) * sizeof(double*));
for (j = 0; j < *row; ++j) {
I will proceed debugging the question source upon request.

Reading multi-line characters from a text file

I have to read a maze from a file and store it in a twodimensional array.
The characters I'm reading are stored in a .txt file like this:
######
#....#
#..#.#
. .#..
######
Note that the number of rows and columns can vary depending on the file.
My approach in reading the file so far:
#include <stdio.h>
#include <stdlib.h>
void read_arr(char** a, int x_size, int y_size) {
int i, j;
int tmp;
FILE* file = fopen("lab1.txt", "r");
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp;
printf("Success\n");
}
}
}
void print_arr(char** a, int x_size, int y_size) {
int i, j;
for (i = 0; i < x_size; i++) {
for (j = 0; j < y_size; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
}
int main() {
int x_size, y_size;
printf("What is the size of the maze (<x> <y>)? ");
scanf("%d %d", &x_size, &y_size);
printf("Maze has size %dx%d\n", x_size, y_size);
char** a = malloc(sizeof(char) * (x_size * y_size));
if (!a)
return -1;
printf("Successfully allocated memory!\n");
read_arr(a, x_size, y_size);
print_arr(a, x_size, y_size);
return 0;
}
But all I get from this is a memory error (I'm afraid I cant't give the exact error message, because it is displayed in german).
Another thing I've tried is using fscanf, but that didn't work either.
I'm on Ubuntu, and using gcc to compile my code.
Any help would be much appreciated!
Memory allocation is not correct
char** a = malloc(sizeof(char) * (x_size * y_size));
I guess what you wanted to do is
char** a = malloc(sizeof(char*) * y_size);
for(i = 0; i < y_size; ++i)
a[i]=malloc(x_size);
Also in read_arr function, you access array as arr[j][i], while j is your inner index, and i is outer
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp; ==> a[i][j] = tmp;
printf("Success\n");
}
}

Resources