C: byte-copy unsigned char value
void callback(const unsigned char* data, int len) {
unsigned char copydatahere;
}
data is a pointer-to-const situation, that is allocated in library outside. len is a size of data, guessing it to be sizeof(unsigned char)*N.
How I allocate copydatahere
to size of len
and copy the whole memory behind data
including null开发者_开发问答 bytes, string termination chars and anything other that has byte representation? What would be the difference between bcopy and memcpy in this situation?
Addition:
memcpy(pointer+offset, sourcedata, size);
that's how you can do 'memcpy append' guys. Thank you all!
Use memcpy
. bcopy
is only supported on some platforms, and is deprecated in newer standards.
void callback(const unsigned char* data, int len) {
unsigned char* copydatahere = malloc(len);
if (!copydatahere) {
exit(1);
}
memcpy(copydatahere, data, len);
/* ... */
free(copydatahere);
}
Allocate with malloc(3)
, release with free(3)
. bcopy(3)
, while deprecated (so prefer memmove(3)
), handles overlapping memory regions, memcpy(3)
doesn't.
#include <assert.h>
#include <stdlib.h>
void callback(const unsigned char *data, int len) {
assert(len >= 0);
unsigned char *copy = malloc(len);
if (copy == NULL) { abort(); }
memcpy(copy, data, len);
/* TODO: Store the length somewhere, since otherwise the pointer is useless. */
/* TODO: pass the pointer "copy" somewhere, so it is used. */
}
Usually the second argument to such a callback function is some unsigned type like unsigned int
or size_t
. Therefore I added the assert
, just to be sure that there won't be any undefined behavior.
memcpy
is well-defined in the C standard, while bcopy
is the old version and is not guaranteed to exist or even work as you expect. (Though usually if it exists it will do what you expect.)
Just create an array
void callback(const unsigned char* data, int len) {
unsigned char copydatahere[len];
memcpy(copydatahere, data, len);
}
If len
can be arbitrarily large (say, like 4 million), it's better to use malloc
though, because it can tell you whether allocation succeeded or not (although some operation systems in certain configurations will lie to you, telling you enough memory is available, only to then later crash when you try to access it). If the above array's allocation fails, behavior is undefined.
Not all compiles support arrays with a variable size, though.
精彩评论