Reputation: 325
I'm traversing a list of nodes which have two fields: next and size. There comes a point in the code where I need to link in a new node and I am having trouble. I've found where the code seg faults and it looks like this. Note that curr is the current node in the list and I need to link in temp between curr and curr->next.
Node* temp = NULL;
temp = ((curr + 1) + a_memory_offset_int); //calculate the address where temp should go
temp->next = curr->next; //Seg faults here
temp->size = some_other_int; //Seg faults here as well
curr->next = temp;
Is there some way that I am trying to set the fields for a NULL node? Is there something wrong with the syntax (as I am confident the logic is correct)?
Upvotes: 0
Views: 76
Reputation: 20734
Without seeing more code, I suspect you might not understand what a_memory_offset_int
is doing. It's doing the exactly same thing as the + 1
, that is to say that it's doing pointer arithmetic. This:
temp = ((curr + 1) + a_memory_offset_int);
is equivalent to:
temp = (Node*)(((char *)curr + 1*sizeof(Node)) + a_memory_offset_int*sizeof(Node));
What you probably really want is:
temp = (Node*)(((char *)curr + 1*sizeof(Node)) + a_memory_offset_int);
Note the only difference is the multiplication of a_memory_offset_int
by sizeof(Node)
. More simplified, this is what you want:
temp = (Node*)((char *)curr + a_memory_offset_int) + 1;
Upvotes: 1
Reputation: 40155
Sample program for verification of pointer arithmetic.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int size;
struct node * next;
} Node;
int main() {
void *memory = malloc(10*sizeof(Node));//allocate of Node * 10
Node *curr = memory;
Node *temp = NULL;
temp = curr + 1;
temp->size = 999;
printf("%lu\n", sizeof(Node));
//16
printf("%p,%p\n", (void*)curr, (void*)temp);
//00000000004D67B0,00000000004D67C0 <- difference is 16
int a_memory_offset_int = 16;
temp = curr + a_memory_offset_int;
if(temp > &curr[9])//curr[9] is last element
printf("It is outside the allocated memory\n");//this display
temp = curr + a_memory_offset_int/sizeof(Node);
printf("%d\n", temp->size);//999
return 0;
}
Upvotes: 1
Reputation: 25615
A linked list node's memory address isn't really important - you shouldn't be calculating it yourself, and instead calling malloc, then linking it in.
Something more like this:
Node* temp = NULL;
temp = malloc(sizeof(Node)); // create a new node, allocating fresh memor
temp->next = curr->next; // should be fine now...
temp->size = some_other_int;
curr->next = temp;
Upvotes: 1