I am creating a linked list for a class project that stores some stock market data. I was trying to store some data onto the stack instead of mallocing to the heap. I am trying to do this using memcpy. My code is like this:
struct trade{
int a,b;
float c;
struct trade *n;
};
char stack[100];
int i = 0;
void newNode(struct trade **head, int a, int b, float c){
struct trade *node;
if(i<99){
memcpy(&a,&stack[i],4);
i = i + 4;
node = (struct lnode*) malloc(16);
}
else
node = (struct lnode*) malloc(20);
}
.....
.....
}
My newnode function is called whenever I create a new node and I need to malloc space for it.
I copy the int into the stack array if there is still space in the stack array else I malloc into the heap. I use 20 and 16 because if I am storing the int in the stack then I need to malloc space for the remaining 16 bytes in my struct else I malloc space for 20 bytes.
For some reason I get a segfault when I do this. I would appreciate it if someone could point me in the right direction.
Thanks!
You’ve got your memcpy arguments swapped. The destination should be the first argument:
From the manpage:
If you’re compiling for anything but 32-bit x86, integers and pointers will not be 4 bytes, but e.g. 8 for 64-bit, which would cause problems. You should really use
sizeof(int). This will also affect the 16 and 20, which you can probably replace withsizeof(lnode). These are set to the correct values at compile time, so won’t affect speed.Besides the issue with defining “stack” versus heap: why do you define your stack as a char array rather than int if you’re putting ints in there? It’s possible to use a char array, but it’s a lot easier and less error-prone to just assign rather than memcpy to an array of the same type.
Valgrind is your friend for this kind of debugging. I find myself using it as a standard debugging tool for segfaults and memory leaks.