Memcpy: warning: dereferencing void * pointer

I use the read () function to read 40 characters from a file and you need to copy from offset 10 for length 20. In other words, I need to make memcpy from 10th to 30th character to a new memory address. However, when I run my code (see below), I received a warning message: warning: dereferencing 'void *' pointer

 int main() { void *buffer = malloc(40); int fd = open("example20.txt", O_RDONLY); printf("the value of fd is %d \n", fd); /* read 40 characters from the file */ int bytes_read = read(fd, buffer, 40); void *new_container = malloc(20); /* copy from buffer, starting offset at 10 for length of 20 */ memcpy(new_container, &buffer[10], 20); printf("new_container is %s \n", (char *) new_container); return 0; } 

I am wondering what this error means and how to fix it?

edit1: I found a way to solve the problem: throwing the buffer from void * to a new char * pointer.

 char *buffer2 = (char *) buffer; memcpy(new_container, &buffer2[10], 20); 

edit2: I found a way to use the void * pointer in memcpy: memcpy(new_container, buffer+10, 20) ; the variable "buffer" can thus be of type void *

+4
c file memcpy
source share
3 answers

Change the line

 memcpy(new_container, &buffer[10], 20); 

to

 memcpy(new_container, (char *)buffer + 10, 20); 

This is because &buffer[10] evaluates to &(*(buffer + 10)) , because the array index operator has higher priority than the address of & operator. However, buffer is of type void * , and a pointer-pointer cannot be made on void pointers, because size information is missing. Using a type operator (char *) on buffer provides the necessary size information, so (char *)buffer + 10 equivalent to buffer + 10 * sizeof(char) or the address of the 11 element in the buffer pointed to by the buffer variable.

+4
source share

A warning is related to this:

 &buffer[10] 

void has no size, and the operator [] needs a specific data type to work in a certain way. This warning is probably due to the fact that your compiler supports void* in unsigned char * (for example, gcc has this extension). But this is not a standard. So a warning.

Change this:

 void *buffer = malloc(40); 

For this:

 unsigned char *buffer = malloc(40); 
+6
source share

Error / warning for string

 memcpy(new_container, &buffer[10], 20); 

Here you are trying to access the 11th element of buffer . But since buffer is void * , the execution of buffer[10] is incorrect.

You need to define it as

 char *buffer = malloc(40); 

Similarly for new_container .

+3
source share

All Articles