-1

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

ottocay
  • 29
  • 2
  • ``record* rec`` creates pointer on stack that points to nowhere (null or junk). You should create rec on stack (```record rec```) or use malloc and then fill it on heap – user996142 Oct 21 '15 at 18:57

1 Answers1

1

rec doesn't point to any allocated memory. Dereferencing it yields undefined behavior. Already the line's

char* ptr = rec->buffer;

result is undefined.

Instead of the pointer, just define

record rec;

and initialize ptr like

char* ptr = rec.buffer;
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • Oh I see ... how could I have missed that? Thank you for your speedy help – ottocay Oct 21 '15 at 18:56
  • @ottocay If you have chosen the best answer, accept it. I don't say this because I'm a rep-who*e but because it marks this question as solved and contributes to keep the state of this site clean. – cadaniluk Oct 22 '15 at 14:53