ReallyGoodPie ReallyGoodPie - 1 year ago 86
C Question

Memory issue when trying to assign pointer to new value

I'm having memory issues when trying to assign a new value to a pointer that was previously assigned a NULL value. I'm not too sure how to approach fixing the issue.

Here is my code. It is a linked list.

typedef struct Node {
void* value;
struct Node* next;
struct Node* prev;
} Node;

typedef struct {
Node* head;
Node* tail;
int size;
} LinkedList;

LinkedList* createLinkedList()
LinkedList* linkedList;

/* Assign memory to LinkedList */
linkedList = (LinkedList*) malloc(sizeof(LinkedList));

/* Assign default LinkedList Attributes */
linkedList->head = NULL;
linkedList->tail = NULL;
linkedList->size = 0;

return linkedList;

void insertFirst(LinkedList* linkedList, void* value)
Node* newNode;
Node* prevHead;

newNode = (Node*) malloc(sizeof(Node));

prevHead = linkedList->head;

newNode->next = prevHead;
newNode->prev = NULL;

linkedList->head = newNode;

linkedList->head = newNode;
linkedList->size += 1;


The main function looks like this:

int main(void)
linkedList = createLinkedList();
insertFirst(linkedList, &testValue);
insertLast(linkedList, &testValue);

I know that when I remove
linkedList->head = newNode
, from
, the program runs without any issue but obviously I lose the ability to access the new head value. Besides
, All other functions run correctly when the above is removed.

When running with Valgrind, I get:

Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x10

which to my knowledge means that I am trying to access a value outside of the stack(?) but I have allocated memory for the new node and then pointing the
to the location of the new node.

As I said before, I am unsure about how to approach this problem so any help would be greatly appreciated. Thanks.

Answer Source

The error means the code is trying to access (either read or write) memory location 0x10 (16). This is certainly an access based on a NULL pointer.

That could happen if malloc() fails. It can also occur if you use the prev or next field values before assigning them to a successful malloc result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download