Mala
Mala

Reputation: 14823

writing to a given void* memory location in C

I have a function that takes as one of its parameters "void* buffer". In this function, I need to write to that memory location. However, doing something like

*buffer = "Hello\0Hi\0";

doesn't work because I can't dereference a void* pointer. How do I put a string data into that memory location? Note that I need to copy data, not necessarily a string, as it may contain the null character.

Updated to reflect that strcpy is not enough

Upvotes: 1

Views: 488

Answers (2)

James McNellis
James McNellis

Reputation: 355117

If you string "may contain the null character," then it isn't really a C string.

If you need to copy a certain number of bytes from one memory location to another, regardless of the contents, you can use memcpy. You can get the size of the string literal using sizeof (this size includes the final, implicit null terminator).

Upvotes: 6

EboMike
EboMike

Reputation: 77752

You can't use the assignment operator to copy a string. You'll need to use something like strcat (which, by the way, is VERY unsafe).

You're probably looking for

strcpy( (char *) buffer, "Hello");

Or better still, use strncpy. You absolutely need to pass in the size of the buffer and make sure you don't overrun it, or else you have a HUGE security hole in your application, not to mention the source of countless hard-to-trace bugs.

Upvotes: 3

Related Questions