How to make a copy of a pointer - c++

I'm trying to copy a pointers data to another pointer, so that if I change one, the value in the other doesn't change.
I need this because I am coding a loop where I have two struct pointers, value, and lastValue. In each iteration of the loop I assign value's content to lastValue, and I fill value with new content. The problem is that because both are struct pointers, when I change value, lastValue changes too, and that's not the behavior I want. The code would be something like this (the structs are IplImages from OpenCV):
IplImage *value;
Iplimage *lastValue;
while(1)
{
lastValue=value;
value=cvQueryFrame( capture );//This fills the struct with new information
}
This would work if they where normal structs, but because they are pointers, both end up with the same value. Is there a way to get a copy of a pointer, with the same value, but different address?

value=cvQueryFrame( capture );
when I change value, lastValue changes too
No, it doesn't. The pointer value gets overwritten, as you desire. It is impossible for this line of code to affect lastValue.
but because they are pointers, both end up with the same value
No, it doesn't matter that they are pointers. Pointers are still objects in and of themselves.
However, cvQueryFrame returns a pointer to a buffer which you shall not modify or free as this is done for you:
Note that the image captured by the device is allocated/released by the capture function. There is no need to release it explicitly.
Though the documentation is a little unclear, it seems likely to me that the buffer is only valid until the next call to cvQueryFrame (which will then re-use the allocated memory). So even though lastValue can't and doesn't change, it happens to end up pointing to the new frame anyway.
To get around this, you can explicitly copy the object that lastValue points to:
lastValue = cvCloneImage(value);
Now you probably take on responsibility for freeing it (but again it's not entirely clear from my cursory glance at the documentation):
cvReleaseImage(&lastValue);

The function cvQueryFrame grabs a frame from camera or video file, decompresses and returns it. It returns the pointer to internal OpenCV buffer having the last grabbed frame. That should be the reason why you get the same value. If you want 2 frames, you should create a copy of the image.
IplImage * previousFrame, *currentFrame ;
CvCapture* video = cvCaptureFromAVI("video.avi");
currentFrame = cvQueryFrame( video );
// COPY IMAGE
previousFrame = cvCloneImage( currentFrame );
while(currentFrame = cvQueryFrame( video ))
{
//...
cvCopy( currentFrame , previousFrame);
}
//...

It looks like you're doing the right thing.
last_value = value; //copy pointer
but it isn't really what you want because it isn't the pointer you want to copy, it's the data inside. that's why the old pointer is updated along with the new pointer. I think what you need is a copy of the structure itself.
If the pointer points to some class you write, add a copy constructor method to it, then copy the value of the pointer like so:
last_value = new MyClass(*value); //construct object, copy from what value points to
//change value

Related

What does CString::GetBuffer() with no size parameter do?

Perhaps I'm going insane, but I have tried every search combination I can think of, and I can't find a definition for CString::GetBuffer() with no parameters. Every reference I look up describes CString::GetBuffer( int ), where the int parameter passed in is the max buffer length. The definition in the header is for CSimpleStringT::GetBuffer(). That gave me the following link, which at least acknowledges the existence of the parameterless version, but offers no description of its behavior.
https://msdn.microsoft.com/en-us/library/sddk80xf.aspx#csimplestringt__getbuffer
I'm looking at existing C++ (Visual Studio) code that I don't want to change if I don't have to, but I need to know the expected behavior of CString::GetBuffer(). I'd appreciate it if someone could explain it or point me to some documentation on it.
Although the msdn documentation doesn't really say what GetBuffer without a parameter does, the MFC source code reveals the answer:
return( m_pszData );
So it just returns a pointer to the underlying character buffer. (It also checks to see if the internal data is shared and forks/copies it first).
The code is in atlsimpstr.h
Complete function:
PXSTR GetBuffer()
{
CStringData* pData = GetData();
if( pData->IsShared() )
{
Fork( pData->nDataLength );
}
return( m_pszData );
}
tl;dr
Call CString::GetString().
This is asking the wrong question for the wrong reasons. Just to get it out of the way, here is the answer from the documentation:
Return Value
An PXSTR pointer to the object's (null-terminated) character buffer.
This is true for both overloads, with and without an explicit length argument. When calling the overload taking a length argument, the internal buffer may get resized to accommodate for increased storage requirements, prior to returning a pointer to that buffer.
From this comment, it becomes apparent, that the question is asking for the wrong thing altogether. To learn why, you need to understand what the purpose of the GetBuffer() family of class members is: To temporarily disable enforcement of CString's class invariants1 for modification, until establishing them again by calling one of the ReleaseBuffer() members. The primary use case for this is to interface with C code (like the Windows API).
The important information is:
GetBuffer() should only be called, if you plan to directly modify the contents of the stored character sequence.
Every call to GetBuffer() must be matched with a call to ReleaseBuffer(), before using any other CString class member2. Note in particular, that operator PCXSTR() and the destructor are class members.
As long as you follow that protocol, the controlled character sequence will always be null-terminated.
Given your actual use case (Log.Print("%s\n", myCstring.GetBuffer())), none of the previous really applies. Since you do not plan to actually modify the string contents, you should access the immutable CString interface (e.g. GetString() or operator PCXSTR()) instead. This requires const-correct function signatures (TCHAR const* vs. TCHAR*). Failing that, use a const_cast if you can ensure, that the callee will not mutate the buffer.
There are several benefits to this:
It is semantically correct. If all you want is a view into the character string, you do not need a pointer to a mutable buffer.
There are no superfluous copies of the contents. CString implements copy-on-write semantics. Requesting a mutable buffer necessitates copying the contents for shared instances, even if you are going to throw that copy away immediately after evaluating the current expression.
The immutable interface cannot fail. No exceptions are thrown when calling operator PXCSTR() or GetString().
1 The relevant invariants are: 1 The controlled sequence of characters is always null-terminated. 2 GetLength() returns the count of characters in the controlled sequence, excluding the null terminator.
2 It is only strictly required to call one of the ReleaseBuffer() implementations, if the contents were changed. This is often not immediately obvious from looking at the source code, so always calling ReleaseBuffer() is the safe option.
Documentation is inconclusive. Looking at ATL sources available here (https://github.com/dblock/msiext/blob/d8898d0c84965622868b1763958b68e19fd49ba8/externals/WinDDK/7600.16385.1/inc/atl71/atlsimpstr.h - I do not claim to know if they are official or not) it looks like GetBuffer() without arguments returns the current buffer, cloning it before if it is shared.
On the other hand, GetBuffer(int) with size is going to check (through the call to PrepareWrite and possibly PrepareWrite2) if the current buffer size is greater than requested, and if it is not, it will allocate the new buffer - thus matching MSDN description.
On a side note, PrepareWrite seems to become quite creative in how it checks for two conditions:
PXSTR PrepareWrite( __in int nLength )
{
CStringData* pOldData = GetData();
int nShared = 1-pOldData->nRefs; // nShared < 0 means true, >= 0 means false
int nTooShort = pOldData->nAllocLength-nLength; // nTooShort < 0 means true, >= 0 means false
if( (nShared|nTooShort) < 0 ) // If either sign bit is set (i.e. either is less than zero), we need to copy data
{
PrepareWrite2( nLength );
}
return( m_pszData );
}
Windows API functions often require the input of a character buffer of a certain length. Then use the GetBuffer(int) version. The following code snippet illustrates this and the difference between GetBuffer() and GetString() and the importance of calling ReleaseBuffer() after calling GetBuffer():
CStringW FullName;
if(::GetModuleFileNameW(nullptr,FullName.GetBuffer(MAX_PATH), MAX_PATH) <= 0)
return 0; //GetBuffer() returns PXSTR
FullName.ReleaseBuffer(); //Don't forget!
FullName = L"Path and Name: " + FullName;
std::wcout << FullName.GetString() << L"\n"; //GetString() returns PCXSTR

How to copy data into certain parts of a byte array

I want to create a byte array out of an unknown struct and add a number additionally in the front of this byte array. How do I do this?
I currently have this code:
template <class T>
void CopterConnection::infoToByteArray(char *&bit_data, size_t *msglen,
T data) {
// Determine which kind of element is in the array, will change in the final code
char typeID = -1;
*msglen = sizeof(data);
*msglen += 1; // take in account of typeID
// Create the pointer to the byte representation of the struct
bit_data = new char[*msglen];
// copy the information from the struct into the byte array
memcpy(bit_data, &data+1, *msglen-1);
bit_data[1] = typeID;
}
But this is not working. I guess I use the memcpy wrong. I want to copy the unkown struct T into the positions bit_data[1] to bit_data[*end*]. What is the best way to achieve this?
One possible problem and one definitive problem:
The possible problem is that array indexing starts at zero. So you should copy to bit_data + 1 to skip over the first byte, and then of course use bit_data[0] to set the type id.
The definitive problem is that &data + 1 is equal to (&data)[1], and that will be out of bounds and lead to undefined behavior. You should just copy from &data.
Putting it all together the last to lines should be
memcpy(bit_data + 1, &data, *msglen-1);
bit_data[0] = typeID;
There is another possible problem, which depends on what you're doing with the data in bit_data and what T is. If T is not a POD type then you simply can not expect a bitwise copy (what memcpy does) to work very well.
Also if T is a class or structure with members that are pointers then you can't save those to disk or transfer to another computer or even to another process on the same computer.
There are a few bugs in there, in addition to the fact you are messing around with new.
The memcpy line itself you use &data + 1 as the source which here will be undefined behaviour. It will add sizeof(data) bytes to the address which is copied so in the stack somewhere and whilst "one past the end" is a valid pointer so this address is valid in pointer arithmetic, nothing you read from it will be, nor anything after it.
bit_data[1] is the 2nd character in your buffer.

Adding two LPCWSTR variables

I'm trying to add two LPCWSTR Variables as in
Shader = L"shader.fx"
Path = L"Source/Shaders/"
return Path + Shader
I've tried a thousand different ways, but my latest has been this
LPCWSTR ShaderFile = GetShader(L"shader.fx");
....
LPCWSTR GetShader(std::wstring _Shader)
{
std::wstring ShaderPath = static_cast<std::wstring>(SHADER_DIRECTORY) + _Shader;
LPCWSTR Return = ShaderPath.c_str();
return Return;
}
Now when I put a break point on the return, the value seems fine, return = Source/Shaders/shader.fx as expected. But when I F10 back into my object, the ShaderFile variable turns out to be something completely random, a bunch of what seems like arabic symbols.
Could anyone point me in the right direction of what to do? As I said, the function seems to work fine, just when i F10 through the breakpoint back into my project the variable equals something completely different
What's happening is that you're returning an address to data that's being invalidated by the return, so everything will seem fine before the function returns, but immediately after the result, it's all (at least potentially) garbage.
If at all possible, just return the std::wstring, and somewhere in the calling code call its c_str() member function when you really need it in the form of a raw buffer.
If you can't do that, and simply must return the result as a raw LPCWSTR, then you'll probably have to allocate the space dynamically:
LPCWSTR *ret = new char [ShaderPath.size()];
strcpy(ret, ShaderPath.c_str());
return ret;
Then, the calling code will need to delete [] the memory when it's no longer needed.
You really want to avoid the latter, and just return an std::wstring though. It's much simpler and cleaner, and will save the nearly inevitable problems with either deleting the buffer before you're finished using it, or else forgetting to delete it when you are done using it (still serious problems in C, but essentially unheard of in decently written C++).
The wstring.c_str() returns the internal pointer of the string.
In your case the local variable is destroyed when you exit the function and hence the pointer returned is deallocated and you get unexpected result.
Possible solution would be to copy the string using the method wcscpy()
The problem is that the c_str() method is returning a pointer into the local variable ShaderPath's memory. When the function exits, ShaderPath is destroyed, along with the data pointed to by your LPCWSTR.
Why don't you just store the variable as a wstring, and whenever you need the LPCWSTR you can call c_str()?
std::wstring GetShader(std::wstring _Shader)
{
return static_cast<std::wstring>(SHADER_DIRECTORY) + _Shader;
}
Assuming you had a function Foo(LPCWSTR path), you would use it like:
Foo(GetShader(L"shader.fx").c_str());
or
std::wstring ShaderFile = GetShader(L"shader.fx");
Foo(ShaderFile.c_str());

Passing struct to a function

This works:
struct client {
string address;
int toPay;
int id;
};
int main() {
struct client clients[10];
...
file.read( (char*)&clients, sizeof (clients) );
}
What I want to do, is do those things inside of a function.
But how would I have to pass the struct to the function?
If I pass it likes this, read doesn't work:
void newFunction ( struct client *clients_t) {
...
file.read( (char*)&clients_t, sizeof (clients_t) );
}
This is not going to work, because the string data is not embedded into the struct. Instead, it has a couple of pointers to the string content. That is why file.read( (char*)&clients...) is not going to produce a valid result: the string will point to the place where a saved string once pointed, but it would no longer represent the data of interest.
If you would like to serialize the data like that, embed an entire char array in the struct, with the obvious limitation that there would be a cap on the number of characters and some wasted space.
Remove the & in the file.read() call.
So:
file.read((char *)clients_t, sizeof(*clients_t) * 10 );
You are passing the address of the pointer itself, but what you want is the address of the structure array, and to pass its correct size.
However, while that makes the read technically valid, it won't create string objects for you, so that fragment would only work in the unusual case that you had written out the references to your own objects earlier in the lifetime of that one process.
As a learning experience, reading and writing binary data is a great idea.
IRL, though, usually you don't want to do it at all, except perhaps via a DBMS. It's hard to debug and can be architecture-specific by exposing the byte order. Think YAML, XML, or CSV instead.
Why don't you simply create an object of struct in the function.
It will work that way too.
and then you can access the members of the struct in that function using the object you created.
A struct is just an object, so you treat it just as you would treat other object.
void Foo(client& ClientObj)
{
//anything written in here directly effects the client object you passed
}
notice you need to pass by reference, if not you would only pass a copy of the object.
//in main
client CObj;
Foo(CObj);
&clients_t is a pointer to a pointer.
clients_t is a pointer which is what is required.
void newFunction ( struct client *clients_t) {
...
file.read( (char*)clients_t, sizeof (clients_t) );
}

How to prevent copying a wild pointer string

My program is crash intermittently when it tries to copy a character array which is not ended by a NULL terminator('\0').
class CMenuButton {
TCHAR m_szNode[32];
CMenuButton() {
memset(m_szNode, '\0', sizeof(m_szNode));
}
};
int main() {
....
CString szTemp = ((CMenuButton*)pButton)->m_szNode; // sometime it crashes here
...
return 0;
}
I suspected someone had not copied the character well ended by '\0', and it ended like:
Stack
m_szNode $%#^&!&!&!*#*#&!(*#(!*##&#&*&##!^&*&#(*!#*((*&*SDFKJSHDF*(&(*&(()(**
Can you tell me what is happening and what should i do to prevent the copying of wild pointer? Help will be very much appreciated!
I guess I'm unable to check if the character array is NULL before copying...
I suspect that your real problem could be that pButton is a bad pointer, so check that out first.
The only way to be 100% sure that a pointer is correct, and points to a correctly sized/allocated object is to never use pointers you didn't create, and never accept/return pointers. You would use cookies, instead, and look up your pointer in some sort of cookie -> pointer lookup (such as a hash table). Basically, don't trust user input.
If you are more concerned with finding bugs, and less about 100% safety against things like buffer overrun attacks, etc. then you can take a less aggressive approach. In your function signatures, where you currently take pointers to arrays, add a size parameter. E.g.:
void someFunction(char* someString);
Becomes
void someFunction(char* someString, size_t size_of_buffer);
Also, force the termination of arrays/strings in your functions. If you hit the end, and it isn't null-terminated, truncate it.
Make it so you can provide the size of the buffer when you call these, rather than calling strlen (or equivalent) on all your arrays before you call them.
This is similar to the approach taken by the "safe string functions" that were created by Microsoft (some of which were proposed for standardization). Not sure if this is the perfect link, but you can google for additional links:
http://msdn.microsoft.com/en-us/library/ff565508(VS.85).aspx
There are two possibilities:
pButton doesn't point to a CMenuButton like you think it does, and the cast is causing undefined behavior.
The code that sets m_szNode is incorrect, overflowing the given size of 32 characters.
Since you haven't shown us either piece of code, it's difficult to see what's wrong. Your initialization of m_szNode looks OK.
Is there any reason that you didn't choose a CString for m_szNode?
My approach would be to make m_szNode a private member in CMenuButton, and explicitly NULL-terminate it in the mutator method.
class CMenuButton {
private:
TCHAR m_szNode[32];
public:
void set_szNode( TCHAR x ) {
// set m_szNode appropriately
m_szNode[ 31 ] = 0;
}
};