Reputation: 13
Like I said in the title, I am trying to generate a linked list from an array. P is a structure containing float x and a pointer to the next element in the list. As soon as the gen_list function is called, the first line of code "first->x = V[0]" returns a segmentation fault, this is what I got from the debugger:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007f6 in gen_list (V=0x602010, n=10000, first=0x601068 <first>)
at main.c:46
46 (*first)->x = V[0];
(gdb)
I can't seem to find the problem, please help !!
Here is minimal amount of code needed to recreate the error:
typedef struct Popis {
float x;
struct Popis *next;}P;
P *first;
int main(){
float v[10];
v[0] = 1;
first->x = v[0];
}
My code :
P* gen_list(float V[], int n, P *first) {
first->x = V[0];
P *T = NULL;
P *new = NULL;
T = first;
t1 = clock();
for (int i = 1; i < n; i++) {
new->x = V[i];
T->next = new;
T = new;
}
T->next = NULL;
t2 = clock();
printf("\nTime for creation of linked list is: %dms", t2 - t1);
return first;}
Upvotes: 1
Views: 192
Reputation: 151
The issue is most probably due to the lack of allocated memory. In the " minimal amount of code needed " code snippet there is no memory allocated for your structure and that is the reason why the process is killed. The kernel returns SIGSEGV signal since you attempt to write on memory which has not been allocated (requested) by your program. To solve that you can simply allocate memory by using malloc();
I hope that the code below would help you to solve the issue:
#include <stdio.h>
#include <stdlib.h>
typedef struct Popis {
float x;
struct Popis *next;
}P;
int main(){
P *first;
/*Here we actually create the structure in the memory - we allocate memory for it*/
first = (struct Popis*)malloc(sizeof(struct Popis));
/*This is a simple check if the memory allocation was sucessfull*/
if(!first)
{
fprintf(stderr, "Error has occured during the memory allocation!\n");
exit(1);
}
float v[10];
v[0] = 1;
first->x = v[0];
printf("%f", first->x);
return 0;
}
Upvotes: 0
Reputation: 312
Segmentation fault usually occurs when there is a bad pointer manipulation, for example in your sample code:
typedef struct Popis {
float x;
struct Popis *next;
} P;
P *first;
int main(){
float v[10];
v[0] = 1;
first->x = v[0];
}
Take a look at the variable *first, is a pointer to a Popis struct, now in main function your trying to use *first pointer, but you need to allocate a memory space in order to use it. If you allocate memory before usage with the following code, segmentation fault error will not occur.
first = (P*)malloc(sizeof(P));
Upvotes: 1