Reputation: 39
I wrote a code that return the error of segmentation fault. The code is long but I wrote the essential part of that as follows. Note that All the variables of defined function inside the main functioned are defined and I tested the code ad it does not go inside the Function_1. That is whay I think the problem is about something like declaration
typedef struct node_type
{
int data;
struct node_type *next;
} node;
typedef node *list;
void Function_1(list R, int *Matrix, int Length, int A);
int main()
{
int S = 5;
int A = 1;
int Mat1[5];
//int *Mat = malloc(S*sizeof(int));
int *Mat = &Mat1[0];
printf("Enter the Matrix with length of 10:\n");
for (int i = 0; i < S; i++)
{
scanf("%i", &(*(Mat+i)));
}
list head;
head = (list)malloc(sizeof(node));
head->next = NULL;
for (int i = 0; i < S; i++)
{
printf("%d\t", *(Mat+i));
}
//printf("\nEnter the Array = \n");
//scanf("\n%d", &A);
printf("\nA = %i", A);
Function_1(head, Mat, S, A);
while (head != NULL)
{
printf("%d\t", head->data);
head = head->next;
}
return 0;
}
void Function_1(list R, int *Matrix, int Length, int A)
{
printf("11111");
list tail;
tail = R;
int Counter = 0;
int i = 0;
while (tail != NULL)
{
if (*(Matrix+i) == A)
{
Counter++;
tail->next = (list)malloc(sizeof(node));
tail->next->data = i;
tail->next->next = NULL;
tail = tail->next;
}
i++;
}
R->data = Counter;
printf("%d", Counter);
}
Thanks
Upvotes: 0
Views: 58
Reputation: 3069
With that code you've provided, I can say that the segmentation fault or access violation occurs due to the lack of <stdlib.h>
or <malloc.h>
inclusion, causing malloc
to be assumed, and then head
to get assigned with something else than what you'd expect.
I don't know, it might also be happening due to random dots in your code...
As per your latest edit, within your loop inside your function Function_1
, you are attempting to access the contents of the memory locations Matrix + i
, with i
having no bounds. It is fine to access there for i
equals 0
to 4
but not after that, and there is nothing holding it from growing any larger.
Consider changing your while
condition into i < 5
or something like that. I couldn't find out what your aim could be with while ( R != NULL )
but R
never changes throughout the loop, so that condition won't become false after being true once, or the opposite.
Similar when the while
condition is rather tail != NULL
which will evaluate to 0
only if malloc
failed to allocate memory. i
will most likely exceed 4
before you use up so much memory that malloc
starts failing.
Upvotes: 1