C Segmentation Fault without any reason - arrays

Can anyone please tell me why i have a segmentation fault here?
float element(float** mat,int k, int l, int block_size){
int i_start=k*block_size;
int i_end=(k+1)*block_size-1;
int j_start=l*block_size;
int j_end=(l+1)*block_size-1;
float somma=0;
int c=0;
float media=0;
for(;i_start<=i_end;i_start++){
for(;j_start<=j_end;j_start++){
somma+=mat[i_start][j_start];
c++;
}
}
media=somma/c;
return media;}
Mat* matrixScale(Mat* m, int block_size) {
Mat* new=(Mat*) malloc(sizeof(Mat));
new->rows=m->rows/block_size;
new->cols=m->cols/block_size;
new->row_ptrs=(float**) malloc(new->rows*sizeof(float*));
int i,j,z;
for(z=0;z<new->rows;z++)
new->row_ptrs[z]=(float*) calloc(new->cols,sizeof(float));
for(i=0;i<m->rows;i++){
for(j=0;j<m->cols;j++){
new->row_ptrs[i][j]=elements(m->row_ptrs,i,j,block_size);
}
}
return new;}
I tried using a debugger but it just says that the problem is inside the element function.

Your post needs more detail. The line of the crash, the definition of Mat, what the intent is. etc.
For the future see how to make a Minimal example. You will get a quicker response with the 'C' tag as well. Be sure to post a detailed question or you will get down voted and castigated.
There are multiple issues with the code. The problem seems to around the block size variable.
int i_start=k*block_size;
int i_end=(k+1)*block_size-1;
int j_start=l*block_size;
int j_end=(l+1)*block_size-1;
Passing in a particular i,j combination and multiplying by block size will go past the end of the row_ptrs array. Reading/writing past the end of the array is undefined and will result in a crash generally. Perhaps you meant divide?
This bit is also odd.
for(i=0;i<m->rows;i++){
for(j=0;j<m->cols;j++){
new->row_ptrs[i][j]=elements(m->row_ptrs,i,j,block_size);
}
}
The max index of rows is [m->rows/block_size][m->cols/block_size] but you are going all the way to [m-rows][m->cols]. Unless blocksize is 1 this will crash as it writes past the end of the array.

Related

Unable to detect the reason for segmentation fault?

#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t-->0)
{
long int size;
scanf("%ld",&size);
long int size2=size*size;
long int a[size],b[size2];
long int i=0;
for(i=0;i<size;i++)
{
scanf("%ld",&a[i]);
}
long int j=0;
long int y;
y=2*a[0];
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(i!=0 && j!=0)
{
b[i*size+j]=a[i]+a[j];
y=y^b[i*size+j];
}
}
}
printf("%ld\n",y);
}
}
I was solving for one of the problems on a popular Competitive Coding Websites, I wrote this code it works for most test cases I tried but, they didn't consider it as it gave them an RE(SIGSEV)->(Runtime error due to segmentation fault.), And didn't even provide with the test case where the error sneaked in,
I made sure about the semantics of taking Input for data variables of different types and (Even made sure my code stays within the allowed limit of 50000 bytes.) Can somebody help me understand what is causing the segmentation fault here?
This segmentation fault is caused by allocating too much automatic memory through VLA (variable-length arrays).
I made sure my code stays within the allowed limit of 50000 bytes
Large VLAs may cause undefined behavior even if your program has plenty of memory available for dynamic allocation, because they take memory from the automatic storage (commonly referred to as "stack"). The amount of automatic storage available to your program is usually a fraction of the total memory available to your process.
You can fix this problem by switching to dynamic allocation:
long int *a = malloc(sizeof(long int)*size);
long int *b = malloc(sizeof(long int)*size2);
...
free(a);
free(b);

Segmentation fault: 11

I have a function that looks through a number of matches from an array and find all teams in matches, that meet some conditions. When found they need to be assigned to a new array. The new array should be used as an output parameter.
I get segmentation fault: 11 when I call it. I have tried to debug but cannot seem to get why. Following is declared in main:
TEAM team_least_viewers;
double spectators = 99999;
solve_task_four(round, team, &team_least_viewers, &spectators);
And the function itself:
void solve_task_four(ROUND *round, TEAM *team, TEAM *team_least_viewers, double *spectators) {
int i, j, k = 0;
for(i=0; i<ROUNDS_PR_SEASON; i++) {
for(j=0; j<MATCH_PR_ROUND; j++) {
if(round[i].match[j].year == 2015) {
/* Searching for team name in team[]*/
for(k=0; k<NUMBER_OF_TEAMS; k++) {
/* If it matches */
if (round[i].match[j].home_team == team[k].name) {
team[k].spectators_home_last_year += round[i].match[j].spectators;
}
}
}
}
for(k=0; k<NUMBER_OF_TEAMS; k++) {
if(team[k].spectators_home_last_year < *spectators) {
*spectators = team[k].spectators_home_last_year;
}
}
}
}
The structs as requested:
typedef struct {
char weekday[WEEKDAY_SIZE], start_time[START_TIME_SIZE],
home_team[TEAM_SIZE], away_team[TEAM_SIZE];
double spectators;
int day, month, year, round, home_team_score, away_team_score;
} MATCH;
typedef struct {
MATCH match[MATCH_PR_ROUND];
} ROUND;
typedef struct {
char *name;
int points, matches_played,
matches_won, matches_draw, matches_lost,
matches_won_home, matches_won_away,
goals_for, goals_against, goal_difference;
double spectators_home_last_year;
} TEAM;
Any help is much appreciated.
I infer your questions is: How do I figure out what is causing the segmentation fault? If that's right, then one answer is to use a debugger. Another answer would be to add print statements throughout the code. The segfault is almost certainly one of the array indexings, like round[i] or round[i].match[j], so be sure to print the i and j values. You may be indexing past the end of an array or dereferencing a null pointer or an uninitialized pointer, so print the pointer values, like printf("round[%d] at %p\n", i, &round[i]).
SIGSEGV on several operating systems is signal 11, and is delivered to the process on a segmentation fault.
Segmentation faults occur when your program accesses memory in a way which isn't allowed, usually by attempting to dereference a null pointer or running off the end of an array.
In your program, the most likely culprits are are array indexes, round[i].match[j] and team[k]. (Another possibility would be if the spectator argument passed were not a valid location for writing, but this is unlikely in this particular case.) You may wish to insert code/run in a debugger to check whether each access is correct.
In particular, assuming that your ROUNDS_PR_SEASON &c. values are correct, it seems most likely that some round[i].match contains a null, if your round array was not fully initialized.

Understanding memory allocation and a core dumped error

I'm a bit confused with memory allocation.
I want to fill a structure Sudoku with random number and then check if a box of 9 numbers are correct.
#define SUDOKU_SIZE 9
typedef struct
{
int grid[SUDOKU_SIZE][SUDOKU_SIZE];
} sudoku_t;
int main(int argc, char const *argv[]){
sudoku_t *s=malloc(sizeof s);
s->grid[0][0]=6;//manualy setting the value of the sudoku
...
s->grid[8][8]=7;
fill_sudoku_test(s);//fill s, a feasible Sudoku with random number
int k, l;
for(k=0;k<SUDOKU_SIZE;k+=3){
for(l=0;l<SUDOKU_SIZE;l+=3){
if(correct_box(s,k,l))//check if a box of 3 by 3 contains 9 differents numbers
printf("Box correct at position :%d and %d\n",k,l);
}
}
free(s);
return EXIT_SUCCESS;
}
When I compile this code, I got a core dumped error.
If somebody got a solution, I'm interested
EDIT
Here's the others functions :
void fill_sudoku_test(sudoku_t *s){
int k, l;
time_t t;
srand((unsigned) time(&t));
for(k=0;k<SUDOKU_SIZE;k++){
for(l=0;l<SUDOKU_SIZE;l++){
if(!(s->grid[k][l])) {
s->grid[k][l]=rand()%SUDOKU_SIZE+1;
}
}
}
}
int correct_tab(int value[]){
int i;
int tab[9];
for(i=0;i<SUDOKU_SIZE;i++){
tab[i]=0;
}
for(i=0;i<SUDOKU_SIZE;i++){
if(tab[value[i]-1]==1){
return 0;
}
else{
tab[value[i]-1]=1;
}
}
return 1;
}
int correct_box(sudoku_t *s, int i, int j){
int tab[SUDOKU_SIZE];
int count=0;
int k,l;
for(k=0;k<3;k++){
for(l=0;l<3;l++){
tab[count]=s->grid[i+k][j+l];
}
}
return (correct_tab(tab));
}
sudoku_t *s=malloc(sizeof s);
should be
sudoku_t *s=malloc(sizeof(sudoku_t));
or
sudoku_t *s=malloc(sizeof(*s));
EDIT
in function correct_tab the value[i] can be (and is) 0. Then:
tab[value[i]-1]=1;
and
if(tab[value[i]-1]==1)
access the array out of bounds.
EDIT 2
In correct_tab value array is not intited for the whole SUDOKU_SIZE then some values of array are undefined.
You can, at least, declare it as:
int tab[SUDOKU_SIZE] = {0};
EDIT3
To answer to your comments:
Your init is correct: init numbers are between 1 to 9.
The problem is that correct_tab is called from correct_box is passing tab, a local (stack allocated) array. This means 1 main thing:
its values are not itited to 0. Those value are randoms due to the
stack allocation.
using my EDIT2 code you can set 0 for all values of the array.
BTW your correct_tab function loops the whole tab array, where only some values are extracted from your sudocu_t struct matrix.
This happend due to:
count variable into correct_box function is always 0. You must inc it each time you set a value into tab array.
You should pass the count value to correct_tab function to allow to loop on the real inserted values only.
When you allocate:
sudoku_t *s=malloc(sizeof s);
This only allocates memory sufficient to store a pointer. You probably mean:
sudoku_t *s=malloc(sizeof(*s));
Beyond that, you will need to use a debugger to identify which part of the code actually triggered the segmentation fault.
First problem lies in this line:
sudoku_t *s=malloc(sizeof s);
which means malloc is allocating memory equal to the size of pointer, which could be 4 bytes or 8 bytes depending on the machine.
Ideally what u r expecting is allocating the size of structure, so this should be:
sudoku_t *s = (sudoku_t *) malloc(sizeof(sudoku_t));

C: Free temporary array produced by malloc-function

I have a c function that produces my a int array using malloc. It works quiet well and I think it isn't really important what it does because the problem doesn't really have anything to do with that. (In this case it calculates the numbers to a given int and base). I need this array temporary in a function, which might be a sub function of a sub function of a ... (you got the idea, point this function can be used several times) and before the return I would like to run free, but it doesn't work. Here is a testing code (it sorts an array of ints to the amount of ones in their binary representation using qsort (yes I know could have calculated the results more directly, but the point is the probleme I run into when trying to run free (here comment out in function ones))):
#include <stdio.h>
#include <stdlib.h>
int values[] = { 88, 56, 100, 2, 25, 0, 15};
int * baseString(int u, int base);
int abs(int a);
int ones(int a);
int cmpfunc (const void * a, const void * b)
{
return ones(*(int*)a)>ones(*(int*)b);
}
int main()
{
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 7; n++ )
{
printf("%d ", values[n]);
}
qsort(values, 7, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 7; n++ )
{
printf("%d (Ones=%d) ", values[n], ones(values[n]));
}
printf("\n");
return(0);
}
int abs(int a){
return (a<0)? a*-1:a;
}
int* baseString(int u, int base){
int* r=malloc(sizeof(int));
r[0]=base;
r[1]=1;
if(base<2){
r[2]=-1;
return r;
}
int negativ=0;
if(u<0){
u=abs(u);
negativ=1;
}
int i=2;
do{
int ur=u%base;
r[i]=ur;
u/=base;
i++;
}while(u>0);
r[1]=i-1;
if(negativ){
r[1]=-r[1];
}
return r;
}
int ones(int a){
int* ai=baseString(a, 2);
int a1=1;
for(int i=2; i<abs(ai[1]); i++){
if(ai[i]==1){
a1++;
}
}
if(!a){
a1=0;
}
//free(ai);
return a1;
}
PS: I am quiet sure this thread is duplicate of some tread somewhere, but I didn't found it.
Part of your problem is actually quite simple.
In your baseString() function, the first three lines are
int* r=malloc(sizeof(int));
r[0]=base;
r[1]=1;
The malloc() dynamically allocates a single int, or an array with one element. The r[1] = 1 modifies the second element of that array which has one element.
The result of that is undefined behaviour. A common symptom of running off the end of an array like this is corrupting memory in your program, such as that used internally by malloc() and free() to keep track of allocated and released memory. Which would explain your problem.
Make sure you allocate the number of elements needed. For example, if 10 elements are needed, malloc(10*sizeof(int)). You need to work out the number needed, since dynamically arrays will not magically grow to get the number of elements needed.
I haven't look further, so there may be other problems. But this one is pretty glaring.
It is also a good idea to check that malloc() actually succeeds. It returns NULL if it fails.
The key problem here appears to an ABW (Array Bounds Write). In the baseString function, you are actually allocating memory which is equivalent to the size of 1 integer, but are trying to access it like an array in r[1],r[2], r[i] etc, which results in write to memory which technically doesn't belong to you.
The code snippet in your code corresponds to
int* r=malloc(sizeof(int));
r[0]=base;
r[1]=1; //ABW here
if(base<2){
r[2]=-1; //ABW here
return r;
}
do{
int ur=u%base;
r[i]=ur; //ABW here
u/=base;
i++;
}while(u>0);
This might lead to undefined behavior at any point of time in your code. In your case, it seems to be affecting free as the memory overwrite may have messed up with the internal book keeping data of malloc and free implementation.

Passing uninitialized 2D arrays as arguments in C

all. I've tried and tried to get my head around this, and feel I am almost there, but I'm getting so confused with how many '*' I need! I have a function that takes as input the string of a directory containing a data file, an int and pointers to two uninitialized 2D arrays. The function reads the data file and then allocates memory and fills the arrays accordingly.
This code is completely wrong, I know, but the idea is:
void main()
{
double **Array1;
int **Array2;
int dimension1;
char DirWork[100], buff[100];
f_ReadData(DirWork, dimension1, &Array1, &Array2);
sprintf(buff,"%lf",Array1[0][0]); // Causes segmentation fault
printf(buff);
}
and
void f_ReadData(char *DirWork, int dimension1, double ***Array1ptr, int ***Array2ptr)
{
int ct, ct2;
double **Array1 = *Array1ptr;
int **Array2 = *Array2ptr;
char FullDirArray1[100], FullDirArray2[100];
FILE *d_Array1, *d_Array2;
sprintf(FullDirArray1,"%s%s,DirWork,"Array1.dat");
sprintf(FullDirArray2,"%s%s,DirWork,"Array2.dat");
d_Array1=fopen(FullDirArray1,"r");
d_Array2=fopen(FullDirArray2,"r");
fscanf(d_Array1,"%d", &dimension1);
Array1 = dmatrix(0,dimension1-1,0,3); // allocates memory to Array1 (dimension1 x 3) elements, using nrutil
Array2 = imatrix(0,dimension1-1,0,3); // allocates memory to Array2 (dimension1 x 3) elements, using nrutil
for(ct=0; ct<dimension1; ct++)
{
for(ct2=0; ct2<3; ct2++)
{
fscanf(d_Array1, "%lf", &Array1[ct][ct2];
fscanf(d_Array2, "%d", &Array2[ct][ct2];
}
}
fclose(d_Array1);
fclose(d_Array2);
}
I've missed out error handling here, but I do have some of that in place... not that it's helping. I'm getting a segmentation fault when I try to access the arrays from the main function.
If anyone could help, I'd really appreciate it... I'm seeing *stars! Thank you!
Then number of stars is correct.
You are getting a segfault because you don't copy back the pointer to the buffers that you allocated. You initialize only f_ReadData:Array1 but you need to assign this value back to *Array1ptr.

Resources