Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy: warning: dereferencing ‘void *’ pointer

Tags:

c

file

memcpy

I use the read() function to read in 40 characters from a file, and need to copy from the offset of 10 for the length of 20. In other words, I need to do memcpy from the 10th to 30th characters into a new memory address. When I run my code (see following), however, I got the 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 of solving the problem: by casting the buffer from void* to a new char* pointer.

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

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

like image 847
TonyGW Avatar asked Dec 06 '22 02:12

TonyGW


2 Answers

Change the line

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

to

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

That's because &buffer[10] evaluates to&(*(buffer + 10)) because the array subscript operator has higher precedence than the address of operator &. However, buffer is of type void * and pointer arithmetic cannot be done on void pointers because there is no size information. Using the typecast operator (char *) on buffer provides the necessary size information so that
(char *)buffer + 10 is equivalent to buffer + 10 * sizeof(char) or the address of the 11th element in the buffer pointed to by the variable buffer.

like image 159
ajay Avatar answered Dec 13 '22 02:12

ajay


The warning is due to this:

&buffer[10]

void has no size, and the [] operator needs a concrete data type to operate in a defined manner. That this is a warning is probably due to your compiler supporting void* in an unsigned char * manner (gcc has this extension, for example). But it isn't standard. Thus the warning.

Change this:

void *buffer = malloc(40);

To this:

unsigned char *buffer = malloc(40);
like image 36
WhozCraig Avatar answered Dec 13 '22 01:12

WhozCraig