pointers - Read memory block in C -
i have assignment need read , write memory block (pre-allocated), so, need implement 2 functions:
memory_read(base,offset,size); memory_write(base,offset,size,buffer);
no problem far, implemented writing part. problem memory_read. need return chunk of data (perhaps void*), can cast whatever expecting outside , use it.
just example. let's have written serialised structure memory. this
void *variable; variable = memory_read(pointer_to_where_it_is,offset,sizeof(some_structure); (some_structure) variable // , use
and memory_read does
void *memory_read(void *base, int offset, int size){ void *buffer; buffer = malloc(size); memcpy(&buffer,base+offset,size); return buffer; }
of course, since buffer lives in function stack, lose reference on return.
any idea on how it? not allowed modify function parameters teacher, otherwise have passed &variable parameter.
thanks!
in line:
memcpy(&buffer,base+offset,size);
the problem trying copy block of memory stack-allocated-variable buffer
instead of heap-allocated block of memory variable pointing to. fix remove &
:
memcpy(buffer, base+offset, size);
otherwise code fine.
update: don't forget free()
returned buffer allocated memory doesn't "leak" :)
Comments
Post a Comment