Declaration in for gives segmentation fault - c

I'm doing a homework for learning graphs. For that, I'm taking a csv file and I keep that information in a Sensor structure.
#define sensor_amount 70
typedef struct Sensor {
int id;
float x,y,z;
}Sensor;
For getting this struct from file I'm using the following function:
Sensor* get_sensors(char* file_name){
FILE* file = fopen(file_name,"r");
//Skip first line
char* c;
fscanf(file,"%[^\n]",c);
int id = 0;
float x,y,z;
Sensor* sensor_arr = malloc(sizeof(Sensor));
fscanf(file,"%i,%f,%f,%f",&id,&x,&y,&z);
sensor_arr[0].id = id;
sensor_arr[0].x = x;
sensor_arr[0].y = y;
sensor_arr[0].z = z;
int counter = 1;
while(!feof(file)){
fscanf(file,"%i,%f,%f,%f\n",&id,&x,&y,&z);
++counter;
sensor_arr = realloc(sensor_arr,counter*sizeof(Sensor));
sensor_arr[counter-1].id = id;
sensor_arr[counter-1].x = x;
sensor_arr[counter-1].y = y;
sensor_arr[counter-1].z = z;
}
fclose(file);
return sensor_arr;
}
I'm calculating distances between each sensor with following code:
float** get_distances(Sensor* s){
float** a = malloc(sensor_amount*sizeof(float*));
for(int i = 0; i < sensor_amount;i++)
a[i] = malloc(sensor_amount*sizeof(float));
for(int i = 0; i < sensor_amount;i++){
for(int j = 0; j < sensor_amount; j++){
float dis = distance(s[i].x,s[i].y,s[j].x,s[j].y);
a[i][j] = dis;
}
}
return a;
}
Finally in my main i print those values like this:
int i,j;
int main(){
char file_name[] = "sensor_locations.csv";
Sensor* sensors;
sensors = get_sensors(file_name);
float**ar=get_distances(sensors);
for(i=0;i < 70; ++i)
for(j=0;j<70;++j){
printf("(%i,%i)->%f\n",i,j,ar[i][j]);
}
return 0;
}
In main, if I move the declarations of i and j to the for loops, it throws a segmentation fault. But why?

This is designed for array out of bounds bugs:
int counter = 1;
...
++counter;
...
[counter-1]
Instead do
for(int i=0; more_data; i++)
{
sensor_arr[i] = ...;
sensor_arr = realloc(sensor_arr,(i+2)*sizeof(Sensor));
}
Please note Why is “while ( !feof (file) )” always wrong?.
And your use of realloc is wrong, use a tmp pointer for storing the result and check it against NULL before assigning it back to the sensor_arr pointer.

Related

Converting Static 2D Array to Dynamic Array in C

We were asked to convert 2D static array to dynamic array. So I will need to create an array of pointers in which every pointer points to a different row. I have written this code but my code breaks when i=1 on line *(dynamicStr[i] + v) = rowStr[v]; Additionally, if I enable free(ptr); section my debugger gets stuck there for 6 or 7 times and then contiunes.
EDIT: In the end, I solved the problem with appying the answers #dodooft and #Viktor Terziev gave.
#include <stdio.h>
#include <stdlib.h>
void toDynamic(int x,int y, char toDyna[x][y]);
void toDynamic2(int x,int y, char toDyna[x][y]);
int main()
{
char toDyna[7][12] = {
"JOHN",
"MARK",
"PIERCEPIERCE",
"20",
"ROSIE",
"ALEX",
"MARLYN"
};
int x = 7;
int y = 12;
toDynamic2(x, y, toDyna);
return 0;
}
void toDynamic2(int x,int y, char toDyna[x][y]){
char *dynamicStr[x];
int rowToCheck = 0;
int size;
char *ptr;
int c;
for(int i = 0; i < x; i++){
printf("i: %d\n",i);
c = 0;
size = strlen(toDyna[rowToCheck]);
ptr = (char*) malloc(size * sizeof(char));
for(int j = 0; j < y; j++){
if(toDyna[i][j] != '\0'){
*(ptr+c) = toDyna[i][j];
c++;
} else{
break;
}
}
*(ptr+size) = '\0';
printf(" ");
char rowStr[size];
for(int v = 0; v < size; v++){
rowStr[v] = *(ptr+v);
printf("Added Char: %c\n", rowStr[v]);
*(dynamicStr[i] + v) = rowStr[v];
}
//free(ptr);
//printf("\n%s\n", rowStr);
//dynamicStr[i] = &rowStr;
rowToCheck++;
}
for(int i = 0; i < x; i++){
printf("%s\n", dynamicStr[i]);
}
}
EDIT: This is the working verion of the code:
#include <stdio.h>
#include <stdlib.h>
char** toDynamic(int x,int y, char toDyna[x][y]);
void free2DArray(int x, char **dynamicStr);
int main()
{
char toDyna[7][12] = {
"JOHN",
"MARK",
"PIERCEPIERCE",
"20",
"ROSIE",
"ALEX",
"MARLYN"
};
int x = 7;
int y = 12;
char **dynamicArr;
dynamicArr = toDynamic(x, y, toDyna);
free2DArray(x, dynamicArr);
return 0;
}
char** toDynamic(int x,int y, char toDyna[x][y]){
printf("Q2\n");
char **dynamicStr;
int rowToCheck = 0;
int size;
int c;
dynamicStr = (char*)malloc(x * sizeof(char*));
for(int i = 0; i < x; i++){
dynamicStr[i] = (char*)malloc(y * sizeof(char));
c = 0;
size = strlen(toDyna[rowToCheck]);
char *ptr = (char*) malloc((size + 1) * sizeof(char));
for(int j = 0; j < y; j++){
if(toDyna[i][j] != '\0'){
*(ptr+c) = toDyna[i][j];
c++;
} else{
break;
}
}
*(ptr+size) = '\0';
dynamicStr[i] = ptr;
rowToCheck++;
}
for(int i = 0; i < x; i++){
printf("%s\n", dynamicStr[i]);
}
printf("----------------------------\n");
return dynamicStr;
}
void free2DArray(int x, char **dynamicStr){
printf("Q3\n");
for(int i = 0; i < x; i++){
free(dynamicStr[i]);
printf("dynamicStr %d freed\n", i);
}
free(dynamicStr);
printf("dynamicStr array freed\n");
printf("----------------------------\n");
}
You define dynamicStr as an array of char pointers, when you are trying to assign a value to it with *(dynamicStr[i] + v) = rowStr[v]; you are basically copying the value of rowStr[v] to the address that is pointed by dynamicStr[i] + v. That address is not defined in your code, so you got a segfault.
If you are trying to fill dynamicStr with pointers to new arrays with dynamic memory, you should try something like
dynamicStr[i] = ptr;
where ptr is the pointer returned by the malloc call to the i-th row. Also, as you are working with strings you can use strcpy to copy the data from the static array to the dynamic one.
Its much easier than you think, please refer to strcpy documentation and strlen documentation, and (if you use my code) don't forget to free your memory.
char * * toDynamic2(size_t n, size_t m, char strings[n][m])
{
char * * arr = malloc(n * sizeof(char*));
for(size_t i = 0; i < n; ++i)
{
size_t size = strlen(strings[i]);
arr[i] = malloc((size + 1) * sizeof(char));
strcpy(arr[i], strings[i]);
}
for(size_t i = 0; i < n; ++i)
{
printf("%s\n", arr[i]);
}
return arr;
}

2d array struct giving a segmentation fault

This program fragment should be reading in information in structs which are stored in a 2d way.
But this program fragment gives a segmentation fault after "printf("lel4\n");".
I have the feeling it is in my memory allocation, but I don't know. I looked for answers on the internet and I am doing exactly the same thing as the given answers, but it isn't working.
typedef struct coordinates{
int xposition;
int ypositiony;
char token;
int discovered;
} coordinates
typedef coordinates *coord;
coord **allocMemory(int row, int col){
int i;
coord **city = malloc(sizeof(coord)*col);
assert(city != NULL);
for(i=0; i<col; i++){
city[i] = malloc(sizeof(struct coordinates)*row);
assert(city[i] != NULL);
}
return city;
}
coord **readInfo(int row, int col){
int i, j;
char c;
coord **city = allocMemory(row, col);
for(i=0; i<col;i++){
c = getchar();
for(j = 0; j<ros; j++){
c = getchar();
if(c == '#' || c == '.'){
printf("lel4\n");
(*city)[i][j].xposition = i;
printf("lel5\n");
(*city)[i][j].yposition = j;
(*city)[i][j].token = c;
(*city)[i][j].discovered = 0;
}
}
}
return city;
}
coord **
to
coord *
and
city[i][j].xposition = i;
city[i][j].yposition = j;
city[i][j].token = c;
city[i][j].discovered = 0;

assigned value to dynamic array created in void function doesnt return the same value in main()

I have a problem with dynamic arrays in C. My program was working perfectly, but I was asked to put the creation of dynamic array into a seperate void. I did it, and it still worked great, but then I had to assign a value to a certain point of the created array in void, and make it return the said value, however, what I get is a random value. The function works by sending a pointer and the lenght of required array into void, and then makes the pointer into a dynamic array.
#include <stdio.h>
#include <stdlib.h>
#define MAX 255
void ieskom (int skaiciai[],int n, int *de, int *me, int *n1, int *n2)
{
int i = 0;
int j = 0;
int nr1 = 0;
int nr2 = 0;
int temp = 0;
int temp1 = 0;
int eile = 0;
int eile1 = 0;
int *did;
did = (int*)calloc(n,sizeof(int));
if (did==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
int *maz;
maz = (int*)calloc(n,sizeof(int));
if (maz==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
i = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] < skaiciai[i+1])
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
}
else
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
j = j + 1;
}
}
j = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] > skaiciai[i+1])
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
}
else
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
j = j + 1;
}
}
*de = did[eile];
*me = maz[eile1];
*n1 = nr1;
*n2 = nr2;
free(did);
free(maz);
}
/*int masyvas(x)
{
int y;
y = (int*)malloc(x*sizeof(int));
return y;
}*/
void *masyvas (int *skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
skaiciai[2] = 5;
return skaiciai;
}
int main()
{
int n1 = 0;
int n2 = 0;
int de = 0;
int me = 0;
int i = 0;
int n = 0;
int *skaiciai;
scanf("%d", &n);
// skaiciai = masyvas(n); // naudojant int
masyvas(&skaiciai, n);
printf("2 = %d", skaiciai[2]);
if (skaiciai==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
for (;i < n; i++)
{
scanf("%d", &skaiciai[i]);
}
ieskom (skaiciai, n, &de, &me, &n1, &n2);
if (de > me)
{
printf("Elementu numeriai:");
printf(" %d", n1-de+1);
printf(" %d\n", n1);
printf("\nAtstumas tarp ju: %d", de-2);
}
else
{
printf("Elementu numeriai:");
printf(" %d", n2-me+1);
printf(" %d\n", n2);
printf("\nAtstumas tarp ju: %d", me-2);
}
free(skaiciai);
getchar();
getchar();
return 0;
}
The problem is in void masyvas and printf skaicia[2] - I assign a certain value to skaiciai[2], yet it prints a random one. How do I fix it?
EDIT: Thank you for your answers and explanations, it really helped me a lot! I know have solved my problem, and most importantly, I know why it was a problem in the first place.
First of all, you should translate variables and texts to english (your code lack of comments, this should apply to them too).
Next your masyvas() function returns a pointer to the allocated array (why void* ?!) but when you call it you don't get the returned value.
You have to choose: either you pass a pointer to your function (an array is a pointer, to if you want an array to be allocated from a function you have to pass a pointer to the pointer, so a int **), or you use the returned value.
Allocating with returned value:
// this function allocates a int* tab of size n and set one value
int *allocate_tab(int n) {
int *tmp;
tmp = malloc(n*sizeof(int));
if (tmp == NULL) {
return(NULL); // failed
}
tmp[2] = 5;
return(tmp);
}
// in main (or other function)
int *mytab;
mytab = alloc_tab(45);
Allocating by passing a pointer to the array:
void alloc_tab(int **tab, int n) {
*tab = malloc(n*sizeof(int));
if (*tab == NULL) {
return;
}
(*tab)[2] = 5;
}
// in main (or other)
int *mytab;
alloc_tab(&mytab, 45);
If you can't understand this stuff I guess you should read more about memory, allocation and pointers.
You need to pass a pointer-to-pointer here and do not need to return anything.
void masyvas (int **skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
(*skaiciai)[2] = 5;
}
When you declare int *skaiciai, the variable is a pointer to type int. skaiciai holds the address that points to an int. When you pass &skaiciai, you're passing the address of the address that points to an int. So because this is an address of an address, its a double pointer.

Simple c prog. error: invalid type arguement of unary '*'

this is my first post here and I'm very new to C.
I want to write a program that is able to print matrixes. It should look like:
----
-o--
ooo-
----
So i want that to be printed for the beginning.
My current code is:
// 4. Exercise
// Learn 2d arrays
#include <stdio.h>
char z;
char s;
char m1_ptr;
void createMatrix()
{
for(z = 0; z != 4; z++)
{
for (s = 0; s != 4; s++)
{
printf("%c", *m1_ptr);
}
printf("\n");
}
}
//------------------------------------------------------------------
int main()
{
char o = o;
char c = '-';
// And some variables for the matrix count:
char matrix_1 [4][4] ={{c,c,c,c},{c,o,c,c},{o,o,o,c},{c,c,c,c}};
char *m1_ptr = &matrix_1 [z][s];
createMatrix(matrix_1 [0][0]);
/* for(z = 0; z != 4; z++)
{
for (s = 0; s != 4; s++)
{
printf("%c", matrix_1 [z][s]);
}
printf("\n");
}
*/
return 0;
}
It works if I put the void function into the main, but since there are much more matrixes coming I want to do that in an extra function to make it more readable.
If I compile that I get the error message:
"Line17: Error: invalid type argument of unary '*' ('have int')"
(edit: line 17 is where it says "printf("c......")
I looked at other questions, but since I only understand super simple programs yet that didn't work out for me.
Does anyone know how that could be fixed?
(It would be nice if the answer explains why, since I have very little experience with pointers)
I think your looking for something like this:
#include <stdio.h>
#define ROW 4
#define COLUMN 4
void printMatrix(int rowLength, int columnLength, char matrix[rowLength][columnLength]) {
int rowCount, columnCount;
for(rowCount = 0; rowCount < rowLength; rowCount++) {
for(columnCount = 0; columnCount < columnLength; columnCount++)
printf("%c", matrix[rowCount][columnCount]);
printf("\n");
}
}
int main() {
char o = 'o';
char c = '-';
char matrix_1 [ROW][COLUMN] = {
{c,c,c,c},
{c,o,c,c},
{o,o,o,c},
{c,c,c,c}
};
printMatrix(ROW, COLUMN, matrix_1);
return 0;
}
It prints the pattern you want
#include <stdio.h>
void displayMatrix( char pMatrix[rCount][cCount], int rCount, int cCount )
{
for(int i = 0; i < rCount; i++ ) // one loop for each row
{
for (int j = 0; j < cCount; j++) // one loop for each column
{
printf("%c", pMatrix[i][j]);
}
printf("\n"); // prep for next row
}
}
//------------------------------------------------------------------
static const o = 'o';
static const c = '-';
int main()
{
// And some variables for the matrix count:
char matrix_1 [][] ={{c,c,c,c},{c,o,c,c},{o,o,o,c},{c,c,c,c}};
displayMatrix(matrix_1,
sizeof( matrix_1) / sizeof(matrix_1[0]), // = number of rows
sizeof( matrix_1[0]) ); // = number of columns
return 0;
}

Dynamic array in struct calloc or pointers failing, C

I'm attempting to complete an assignment on sparse matrices in C. I have a sparse matrix held as a list of values and coordinates and am converting it to Yale format.
I have run into a strange memory allocation issue that no one seems to have seen before. My code is:
yale* convertMatrix(matrix_list* input){
int matrix_elements = input->elements;
int matrix_rows = input->m;
yale* yale = (struct y*)calloc(1, sizeof(yale));
int* A = (int*)calloc(matrix_elements, sizeof(int));
int* IA = (int*)calloc(matrix_rows + 1, sizeof(int));
int* JA = (int*)calloc(matrix_elements, sizeof(int));
printf("%d elements\n",matrix_elements);
yale->A = A; // Value
yale->IA = IA; // Row (X)
yale->JA = JA; // Column (Y)
yale->elements = matrix_elements;
yale->m = matrix_rows;
yale->n = input->n;
list* tmp_list = input->first;
for(int i = 0, j = 0, tmp_y = 0; i < matrix_elements && tmp_list!=NULL; i++){
printf("Input Value: %d \n",tmp_list->point.value);
A[i] = tmp_list->point.value;
// Initialise the first row
if(i == 0) IA[0] = tmp_list->point.x;
else{
// Add a new row index
if(tmp_y != tmp_list->point.x){
j++;
IA[j] = i;
tmp_y = tmp_list->point.x;
}
}
JA[i] = tmp_list->point.y;
tmp_list = tmp_list->next;
}
for(int i = 0; i < matrix_elements; i++)
printf("%d,",yale->A[i]);
printf("\n");
for(int i = 0; i < matrix_rows + 1; i++)
printf("%d,",yale->IA[i]);
printf("\n");
for(int i = 0; i < matrix_elements; i++)
printf("%d,",yale->JA[i]);
return yale;
}
And here is the struct for yale:
typedef struct y{
int n;
int m;
int elements;
int *IA;
int *JA;
int *A;
} yale;
But the program segfaults at the first relevant printf on the first iteration of the loop.
printf("%d,",yale->A[i]);
I'm positive:
matrix_elements is an integer (9 in my test case)
matrix_rows is an integer
A / IA / JA are all filled with correct values (if you swap yale->A for A in the printf, it works fine).
Directly callocing the array to the struct pointers doesn't affect the result.
Mallocing, callocing, not typecasting, all no effect.
Thanks to Xcode and gdb I can also see that at the point of the segfault. The structure pointers do NOT seem to point to the arrays
I suggest you run your code under Valgrind. This should report the buffer overflow error. (A buffer overflow is where you write past the end of an array).
I also recommend you write some unit tests for your code. They can be very helpful detecting bugs. In particular, I suggest you write a test with a 3x3 input matrix with a value in every position. Check that the values you get out are what you expect.
To get it compiled, I need to prepend this to the snippet:
#include <stdlib.h>
#include <stdio.h>
typedef struct y{
int n;
int m;
int elements;
int *IA;
int *JA;
int *A;
} yale;
typedef struct list {
struct list *next;
struct point { int x,y,value; } point;
} list;
typedef struct matrix_list {
int elements;
int m;
int n;
struct list *first;
int *point;
} matrix_list;
UPDATE: I transformed the program into something more readable (IMHO). I don't have the faintest idea what the IA and JA are supposed to do, but the below fragment should be equivalent to the OP.
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
struct y {
unsigned int n;
unsigned int m;
unsigned int elements;
unsigned int *IA;
unsigned int *JA;
int *A;
} ;
struct list {
struct list *next;
struct point { unsigned int x,y; int value; } point;
} ;
struct matrix_list {
unsigned int elements;
unsigned int m;
unsigned int n;
struct list *first;
} ;
struct y *convertMatrix(struct matrix_list* input)
{
unsigned int matrix_elements = input->elements;
unsigned int matrix_rows = input->m;
unsigned int ii,jj,tmp_y;
struct y *yale ;
struct list *tmp_list ;
yale = calloc(1, sizeof *yale);
assert (yale != NULL);
printf("%u elements\n",matrix_elements);
yale->A = calloc(matrix_elements, sizeof *yale->A);
assert (yale->A != NULL);
yale->IA = calloc(matrix_rows + 1, sizeof *yale->IA);
assert (yale->IA != NULL);
yale->JA = calloc(matrix_elements, sizeof *yale->JA);
assert (yale->JA != NULL);
yale->elements = matrix_elements;
yale->m = matrix_rows;
yale->n = input->n;
// Initialise the first row, set start condition
// FIXME: this ignores the empty list or size=0 cases
yale->IA[0] = tmp_y = input->first->point.x;
ii = jj = 0;
for(tmp_list = input->first ;tmp_list; tmp_list = tmp_list->next) {
printf("Input Value: %d \n",tmp_list->point.value);
yale->A[ii] = tmp_list->point.value;
// Add a new row index
if(tmp_y != tmp_list->point.x){
jj++;
yale->IA[jj] = ii;
tmp_y = tmp_list->point.x;
}
yale->JA[ii] = tmp_list->point.y;
if (++ii >= matrix_elements ) break;
}
for(int i = 0; i < matrix_elements; i++)
printf("%d,",yale->A[i]);
printf("\n");
for(int i = 0; i < matrix_rows + 1; i++)
printf("%u,",yale->IA[i]);
printf("\n");
for(int i = 0; i < matrix_elements; i++)
printf("%u,",yale->JA[i]);
return yale;
}
Note: I moved the (ii == 0) {} condition out of the loop, and replaced the one-letter indices by there two-letter equivalents. Also: all the indices are unsigned (as they should be)

Resources