replax replax - 1 year ago 74
C Question

C: struct initialisation of linked list resulting in access violation exception

I have a question regarding linked-lists/structs in C. I am trying to add vertices to a linked list and populate them with data.
Why do I get an access violation at

newHead->name = newVertexName
even though I assgined memory to newHead beforehand?

Code for context:

typedef struct Vertex Vertex;

typedef struct Vertex
char name;
Vertex *next;
} Vertex;

struct Vertex* AddVertex(Vertex* head, char newVertexName)
Vertex* newHead = malloc(sizeof(Vertex));
newHead->name = newVertexName; // Access violation occuring here
newHead->next = head;
return newHead;

int main()
char s[100];
const int nNrOfVerts = 27;
Vertex* adjList[28];

for(int i = 0; i <= nNrOfVerts; ++i)
adjList[i] = NULL;

for(int i = 1; i <= nNrOfVerts; ++i)
if(scanf("%s", s) == 1)
adjList[i] = AddVertex(adjList[i], s[i-1]);

return 0;

thank you!

Answer Source

First of all, you have to include files:

#include <stdlib.h> /* for malloc/free */
#include <stdio.h>  /* for scanf */

It's fix your access violation.

Secondly, I think you have bug here:

adjList[i] = AddVertex(adjList[i], s[i-1]);


adjList[i] = AddVertex(adjList[i-1], s[i-1]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download