Segmentation fault in 2D array Dynamic Allocation - c

#include<stdio.h>
#include<stdlib.h>
struct Graph{
int V;
int E;
int **Adj;
};
struct Graph* adjMatrix(){
int u,v,i;
struct Graph *G;
G=(struct Graph*)malloc(sizeof(struct Graph));
if(!G){
printf("Memory Error!\n");
return;
}
printf("Enter number of nodes and number of edges:\n");
scanf("%d %d",&G->V,&G->E);
G->Adj=malloc((G->V)*(G->V)*sizeof(int));
for(u=0;u<(G->V);u++)
for(v=0;v<(G->V);v++)
G->Adj[u][v]=0; //This gives a segmentation fault.
printf("Enter node numbers in pair that connect an edge:\n");
for(i=0;i<(G->E);i++){
scanf("%d %d",&u,&v);
G->Adj[u][v]=1;
G->Adj[v][u]=1;
}
return(G);
}
int main(){
struct Graph *G;
int i,j,count=0;
G=adjMatrix();
for(i=0;i<G->V;i++){
for(j=0;j<G->V;j++){
printf("%d ",G->Adj[i][j]);
count++;
}
if(count==G->V)
printf("\n");
}
return 0;
}
The code shows segmentation fault when I tried to assign a value in 2D array i.e. at G->Adj[u][v]=0; but I don't know what is wrong with that? Because It's simply a assignment to the array.

#include<stdio.h>
#include<stdlib.h>
struct Graph{
int V;
int E;
int **Adj;
};
struct Graph* adjMatrix(){
int u,v,i;
struct Graph *G;
G=malloc(sizeof(struct Graph));
if(!G){
printf("Memory Error!\n");
return 0;
}
printf("Enter number of nodes and number of edges:\n");
scanf("%d %d",&G->V,&G->E);
//First problem was here this is how you allocate a 2D array dynamically
G->Adj=malloc((G->V)*sizeof(int*));
for(u=0;u<G->V;u++)
G->Adj[u]=malloc((G->V)*sizeof(int));
for(u=0;u<(G->V);u++)
for(v=0;v<(G->V);v++)
G->Adj[u][v]=0; //This gives a segmentation fault.
// i added some adjustment here to help you
printf("Enter node numbers in pair that connect an edge:\n");
for(i=0;i<(G->E);i++){
scanf("%d %d",&u,&v);
if(u>=G->V || v>=G->V){
printf("Error give the right input\n");
i--;}
else{
G->Adj[u][v]=1;
G->Adj[v][u]=1;}
}
return(G);
}
int main(){
struct Graph *G;
int i,j,count=0;
G=adjMatrix();
for(i=0;i<G->V;i++){
for(j=0;j<G->V;j++){
printf("%d ",G->Adj[i][j]);
count++;
}
if(count==G->V)
printf("\n");
}
return 0;
}

The segmentation fault is casued due-to error at the 2D array allocation method, as it us done at the following line:
G->Adj=malloc((G->V)*(G->V)*sizeof(int));.
which actually allocated a 1D buffer of (G->V)*(G->V) integers, so it can't enable a later access in syntax of 2D, like you want
In a nutshell: when allocation 2D array like you wish, you should first allocate the 1D array of pointers.
At your code, should be:
G->Adj = (int **)malloc(sizeof(int *)*G->V);
And then allocate G->V vectors per pointer:
for(i=0; i < G->V; i++)
{
G->Adj[i] = (int *)malloc(sizeof(int)*G->V);
}
furthermore, a good practice is to verify allocation result is not NULL (malloc failure), for each allocation
for general explanation on c vectors allocation you may read more at Method 2: the "can still use [r][c] syntax to access" way
Besides that, memory release is missing at the end of your program, so you should add calls to free() at the opposite order (vectors and then pointers)

Related

Why my code runs up to point A and crashes when I give B coordinates?

I am new at C pointers and I'm trying to find the error.
Any help is appreciated.
The code compiles without any errors. When it runs, it accepts point A coordinates but crashes when I input B coordinates.
The output I get is this:
Give Coordinates...
Give A(x1,y1):
2
3
Give B(x2,y2):
4
zsh: bus error ./a.out
andreas#Andreas %
Code:
#include <stdlib.h>
struct point
{
int x;
int y;
};
struct triangle
{
struct point *A;
struct point *B;
struct point *C;
};
void initialiseTriangle(struct triangle *);
int main()
{
system("clear");
struct triangle triangle1, *trianglePtr;
trianglePtr = &triangle1;
initialiseTriangle(trianglePtr);
return 0;
}
void initialiseTriangle(struct triangle *object)
{
printf("Give Coordinates...\n");
printf("Give A(x1,y1): \n");
scanf("%d", &object->A->x);
scanf("%d", &object->A->y);
printf("Give B(x2,y2): \n");
scanf("%d", &object->B->x);
scanf("%d", &object->B->y);
printf("Give C(x3,y3): \n");
scanf("%d", &object->C->x);
scanf("%d", &object->C->y);
}```>quote
It is because you allocate space for the triangle, but not for the point pointers.
You could either allocate memory (here on the stack) :
int main()
{
system("clear");
struct triangle triangle1, *trianglePtr;
struct point pointA, pointB, pointC;
triangle1.A = &pointA;
triangle1.B = &pointB;
triangle1.C = &pointC;
trianglePtr = &triangle1;
initialiseTriangle(trianglePtr);
return 0;
}
or directly put the point structs into the triangle struct, instead of using pointers :
struct triangle
{
struct point A;
struct point B;
struct point C;
};

Stack with a dynamic array: segfaults when popping value multiple times

I have a stack implemented with a dynamically allocated array, which is populated using scanf(). The push function works properly, except that when I print out the stack, I always get two extra zeros at the beginning of the output. Attempting to pop the stack only pops the zeroes, and it segfaults once the popping happens twice. I can't figure out where this issue is occurring.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Creates struct of stack*/
typedef struct Stack{
int *ptArray;
int top;
int stackSize;
int itemsInStack;
} Stack;
/*Initialized stack*/
Stack* stackInit(){
Stack *a;
a= (Stack*) malloc(sizeof(Stack));
a-> ptArray=(int*) malloc(sizeof(int)) ;
a-> top=0;
a-> stackSize=1;
return a;
}
void stackPush( Stack *stx, int val){
if( (stx->top) == (stx->stackSize)){
grow(&stx->ptArray, &stx->stackSize);
}
stx->ptArray[stx->top]= val;
stx->top++;
stx->itemsInStack++;
}
/*Grows astack array when space runs out*/
void grow(int** array, int *sz){
int *temp;
temp= (int*) malloc(sizeof(int)* (*sz+2) );
int i;
for( i=0; i< *sz; i++)
temp[i]=( *array)[i];
free(*array);
*array= temp;
*sz=*sz+2;
}
void stackPop( Stack* stx){
free(stx->ptArray[stx->top]);
stx->top--;
stx->stackSize--;
stx->itemsInStack--;
}
void showStack(Stack* s){
int i;
printf("\n");
for(i=s->stackSize; i>-1; i--){
printf("%d\n", s->ptArray[i]);
}
}
void main(int argc, char** argv){
Stack *stackArray;
stackArray= stackInit();
int val=0;
while (val != -999) {
scanf("%d", &val);
if (val == -999) {
break;
}
stackPush(stackArray, val);
}
showStack(stackArray);
stackPop(stackArray);
stackPop(stackArray);
showStack(stackArray);
stackPop(stackArray);
showStack(stackArray);
}
You have a problem in your malloc / free couples.
You allocate the array like this :
a-> ptArray=(int*) malloc(sizeof(int)) ;
If you need to grow the stack you allocate a new array like this :
temp= (char*) malloc(sizeof(char)* (*sz+2) );
So you allocate the whole array at one.
But for some reasons , when you are poping an item you do this :
free(stx->ptArray[stx->top]);
You never allocated this. you allocated ptArray so if you have to free something , it is ptArray.
Just like you did in your grow function :
free(*array);
I hope your error is clear now.This is what is causing the segmentation fault. However you still have some issues with the management of your stack.

Why this program crashes?

This small C program is crashing every single time.
It is supposed to allocate a chunk of memory under the form of a 3D grid composed of many structures (cells) disposed in memory in a 3D-friendly pattern. The structs will be populated with position data.
I don't know why it crashes. It returns this number: c0000005.
#include <stdio.h>
#include <malloc.h>
typedef struct {
int coords[3];
} cell;
int main() {
int x=4, y=8, z=6;
int volume=x*y*z;
cell *arr=(cell*)calloc(volume,sizeof(cell));
int u=0,v=0,w=0;
int index;
for (w=0; w<z; w++) {
for (v=0; v<y; v++) {
for (u=0; u<x; u++) {
//printf("%d %d %d\n", u, v, w);
index=u+v*y+w*y*z;
arr[index].coords[0]=u;
arr[index].coords[1]=v;
arr[index].coords[2]=w;
//getchar();
}}}
printf("All done.\n");
return 0;
}
The problem is index=u+v*y+w*y*z;.
It should be index=u+v*x+w*y*x;.
So #nos is right. It triggers a segmentation fault because 6=z>x=4 and index becomes too large.

Program with array of structs crashes

I have an array with multiple structs. When i ask the user to enter data the first time everything works but when i ask again for the next position in the array the program crashes. If this method doesn't work souldn't the program crash in the beginning? Is something wrong with malloc?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[50];
int semester;
};
struct prof {
char name[50];
char course[50];
};
struct student_or_prof {
int flag;
int size;
int head;
union {
struct student student;
struct prof prof;
}
}exp1;
struct student_or_prof *stack;
void init(int n)
{
stack = malloc(n);
}
int push(struct student_or_prof **pinx,int *head,int n)
{
char name[50];
printf("\nn= %d\n",n);
printf("\nhead= %d\n",*head);
if(*head==n)
{
printf("Stack is full.\n");
return 1;
}
char x;
printf("Student or Professor? [s/p] ");
getchar() != '\n';
scanf("%c",&x);
if(x=='s')
{
getchar() != '\n';
pinx[*head]->flag = 0;
printf("\n\nGive student's name: ");
fgets(pinx[*head]->student.name,sizeof(pinx[*head]->student.name),stdin);
printf("\nGive student's semester: ");
scanf("%d",&(pinx[*head]->student.semester));
printf("\nName = %s\tSemester = %d",pinx[*head]->student.name,pinx[*head]->student.semester);
}
else if(x=='p')
{
getchar() != '\n';
pinx[*head]->flag = 1;
printf("\n\nGive professor's name: ");
fgets(pinx[*head]->prof.name,sizeof(pinx[*head]->prof.name),stdin);
printf("\nGive course: ");
fgets(pinx[*head]->prof.course,sizeof(pinx[*head]->prof.course),stdin);
printf("\nName = %s\tCourse = %s\n",pinx[*head]->prof.name,pinx[*head]->prof.course);
}
(*head)++;
printf("\nhead= %d\n",*head);
}
int main()
{
int n,i;
printf("Give size: ");
scanf("%d",&n);
init(n);
for(i=0;i<n;i++)
push(&stack,&exp1.head,n);
return 0;
}
You need to malloc the structure not n
malloc(sizeof(struct student_or_prof)*n)
EDIT:
And your code crashes again because pinx is a double pointer, so this operation is not valid:
pinx[*head]->flag = 0;
this is equivalent to:
*(pinx + *head)->flag = 0;
Since you are not changing what stack points to, you are better off using a single pointer instead of a double pointer.
So instead you should change your push API:
int push(struct student_or_prof *pinx,int *head,int n)
and call it like:
push(stack,&exp1.head,n);
malloc allocates the given number of bytes.
You have to multiply n with the size of your struct, to allocate enough memory.
pinx does not point to an array, so pinx[*head] is going to access invalid memory unless *head is zero.
I think you meant (*pinx)[*head] , which accesses the N-th element of the array you allocated via malloc. For example (*pinx)[*head].prof.name etc.
BTW, your head number doesn't seem to be used at all, except for exp1.head, maybe it'd be better to remove head from the struct, and just have a single variable head?

Assigning Values to Variables Within Structs Through Pointers in C

Ok so I'm sure there's a simple fix that I'm missing, but right now my code is causing a segment fault on the line "A[i]->key = 0;." The Record* Item part is a necessity for the program, so I need to make it work this way for an assignment I'm working on, however if I do change it so that Item becomes a non-pointer typedef of Record, then I can use A[i].key no problem. I just need a nudge in the right direction so that I can make standInput correctly assign values to an array of pointers to records. Thanks!
Item.h:
#include "stdio.h"
#include "stdlib.h"
typedef int keyType;
struct Record
{
keyType key;
int other;
};
typedef struct Record* Item;
void standInput(Item *A, int n)
{
int i, input;
for(i = 0; i <= n-1; i++)
{
A[i]->key = 0;
printf("%d ", A[i]->key);
}
}
Main:
#include "stdio.h"
#include "stdlib.h"
#include "Item.h"
int main()
{
int n;
Item *A;
printf("Enter a length for the array: ");
scanf("%d", &n);
A = (Item*)malloc(n * sizeof(Item));
standInput(A, n);
return 0;
}
The values in A are all uninitialized, but you're using them as struct Record pointers anyway. If you want to have A continue holding pointers (rather than the structs directly), then you need to allocate space for A and for each item pointed to by A.
Note that Item is already a pointer!
You have to allocate space for the struct, not for the pointer:
A = (Item)malloc(n * sizeof(struct Record));
Note: If the typedef for pointer confuses you, don't use it ;)
A[i]->key means that A[i] is a pointer, but you just allocated an array, so use A[i].key.
Note: you have to change the type of A accordingly.
2nd solution: if you want A[i] to be a pointer, you have to fist allocate space for the pointers (as you do now), then for each pointer (in a loop) allocate space for the struct.
Your structure name is Record not Item. So you should use sizeof(struct Record).
Do it this way:
int main()
{
int n, i;
Item *A;
printf("Enter a length for the array: ");
scanf("%d", &n);
A = (Item*)malloc(n * sizeof(Item));
for(i=0; i<n; i++){
A[i] = (Item)malloc(sizeof(struct Record));
}
standInput(A, n);
return 0;
}

Resources