0

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]);
        }
        else
        {
            break;
        }
    }

    return 0;
}

thank you!

4
  • 1
    Have you verified that malloc is succeeding on every call? Commented Nov 24, 2016 at 23:45
  • @Scott Hunter what exactly do you mean by verifing? The error occurs at the first execution of the statement above... Commented Nov 25, 2016 at 0:14
  • BTW s[i-1] --> s[0] Commented Nov 25, 2016 at 0:26
  • Verifying that malloc is succeeding means checking the result of calling malloc to make sure that it is not NULL. malloc will return NULL if it can't allocate the memory. So with Vertex* newHead = malloc(sizeof(Vertex)); NewHead will be NULL if malloc fails, and then newHead->name = newVertexName; will probably result in an access violation. Commented Nov 25, 2016 at 3:34

1 Answer 1

1

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]);

vs:

adjList[i] = AddVertex(adjList[i-1], s[i-1]);
Sign up to request clarification or add additional context in comments.

1 Comment

The way it currently is, that'd be more like a prev rather than a next pointer ie. that's reverse connecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.