I'm having some trouble with memcpy throwing a segmentation fault, and I can't seem to locate the source of the error.
typedef struct {
int record_code;
char* record_name;
char buffer[6004];
} record;
record* rec;
char* ptr = rec->buffer;
//--DEBUG
printf("ADDR OF PTR: %p\n", ptr);
printf("SIZE OF BUFFER: %d\n", sizeof(ptr->buffer));
//--End DEBUG
create_record(ptr);
I want to add an int value into my buffer, but I'm getting a SEGFAULT on this line
memcpy(ptr, &key, sizeof(key));
in this function
int counter = 0;
int create_record(char* ptr) {
int key = counter;
//--DEBUG
printf("ADDR OF PTR: %p\n", ptr);
printf("SIZE OF KEY: %d\n", sizeof(key));
//--End DEBUG
memcpy(ptr, &key, sizeof(key));
ptr += sizeof(key);
int integer = rand_int();
memcpy(ptr, &integer, sizeof(integer));
ptr += sizeof(integer);
char* word = rand_string();
memcpy(ptr, word, strlen(word));
ptr += strlen(word);
counter++;
}
The only reasons I could think of memcpy throwing a segfault is if either pointers are garbage or the size of the thing I'm trying to throw into the memory location is greater than the memory I have allocated. But I'm merely trying to put an integer (size = 4 bytes) into a buffer allocated to be 6004 bytes, so it doesn't appear to be a sizing issue... and the address of the pointer I have matches what it had been when initially created (I'm not sure if that actually matters tbh...).
The output I get from the prints are these
ADDR OF PTR: 0x10
SIZE OF BUFFER: 64004
(now inside create_record)
ADDR OF PTR: 0x10
SIZE OF KEY: 4
Can anyone tell me where I'm going wrong?
Thanks in advance