Can I reliably use memset and memcpy operators in C++ with memory been allocated with new?
Edited:
Yes, to allocate native data type
Example
BYTE *buffer = 0;
DWORD bufferSize = _fat.GetS开发者_运维技巧ectorSize();
buffer = new BYTE[bufferSize];
_fat.ReadSector(streamChain[0], buffer, bufferSize);
ULONG header = 0;
memcpy(&header, buffer, sizeof(ULONG));
So long as you are only using new to allocate the built-in and/or POD types, then yes. However, with something like this:
std::string * s = new string;
memset( s, 0, sizeof(*s) );
then you would be looking at disaster.
I have to ask though, why you and others seem so enamoured with these functions - I don't believe I ever use them in my own code. Using std::vector, which has its own copy and assignment facilities seems like a better bet for memcpy(), and I've never really believed in the magic of setting everything to zero, which seems to be the main use for memset().
Yes, you can, indeed
Here's a canonical implementation of memset
(taken from the libc of Android):
void* memset(void* dst, int c, size_t n)
{
char* q = dst;
char* end = q + n;
for (;;) {
if (q < end) break; *q++ = (char) c;
if (q < end) break; *q++ = (char) c;
if (q < end) break; *q++ = (char) c;
if (q < end) break; *q++ = (char) c;
}
return dst;
}
It's obvious that the dst
pointer could be allocated any valid way (new
, malloc
, or even statically) - memset
doesn't care.
Yes of course, though memory allocated with new is taken from the "free store" it is still just in the application memory address space. memset and memcpy simply take address parameters for a source and destination, and these parameters can technically be to any address in your application's address space.
In fact some of the standard library algorithms distill down to a simple memcpy themselves (vector source and target copies through iterators).
Depends what you have allocated. If you have allocated POD (Plain Old Data) i.e. done
char* p = new char[100];then yes, it is no different from malloc. If you have allocated an object(s) then using memcpy or memset could lead to un-defined behavior.
You mentioned using memset, but your code didn't call it.
You can leverage the features of the language to allocate & memset all in one blast:
int someInts [256] = {0};
This will allocate an array of 256 ints, and set each one to zero, accomplishing the same as:
int someInts[256];
memset(someInts, 0, sizeof(someInts));
...but possibly faster, depending on how your compiler will optimize the alloc-memset code block.
精彩评论