A buffer that holds binary chunks of data is supposed to be copied to an array of structs (each struct represents a chunk), each chunk in the buffer is 20 bytes, first 4 bytes hold the hash value, then 8 bytes for an offset info, then 8 for a size:
thats the struct definition:
typedef struct{
khint_t hash; // 4
long int offset_start; // 8
size_t size; // 8
} header_offset, *offset_p;
and below is the code that’s supposed to do whats mentioned:
offset_p *offsets;
size_t s= HEADER_OFFSET_SIZE;
header_offset t_offsets[n_files];
for (i=0; i< n_files; i++){
memcpy(&t_offsets[i].hash, buff, sizeof(khint_t));
buff+= sizeof(khint_t);
memcpy(&t_offsets[i].offset_start, buff, sizeof(long int));
buff+= sizeof(long int);
memcpy(&t_offsets[i].size, buff, sizeof(size_t));
buff+= sizeof(size_t);
printf("hash read: %p\n", t_offsets[i].hash);
printf("offset start read: %p\n", t_offsets[i].offset_start);
printf("offset size read: %p\n", t_offsets[i].size);
}
memmove(offsets, t_offsets, sizeof(header_offset)*n_files);
buff-= s*n_files;
free(buff);
return offsets;
I was struggling copying the chunks directly into a header_p* so i decided to have a temporary struct array thats copied from the buffer, then gets copied to a header_p*, I’d appreciate it even more if you could provide me with a way to do it without using a temporary struct array.
The printfs print the right data, although when calling this function, the array of the pointers returned does not hold the right data, or the same data that was printed within the loop.
I’d like to know, without further code, whether its the way im using pointers that causes the array of offset_p’s not hold the right values.
No memory has been allocated for
offsets,memmove()does not allocate the memory for you:header_offset* offsets = malloc(sizeof(header_offset)*n_files);
Given that your are allocating memory to be returned the use of
t_offsetsis unrequired: just populateoffsetsdirectly.EDIT:
To return a
header_offset*[]as commented by alk: