Poiinters in visual C++ - pointers

How do I use pointer in visual studio every time I declare a pointer using
int *pointer;
I get a build error leave alone other operations with them. Is there something which must be done to use pointers with VC++
Error code C4101
However when I use the pointer in the code I get an error LNK1168
Edit: issue solved restarting the IDE along with assigning a value to the pointer solves it. Thanks.

C4101 is not an error, but a warning and you get it because you just declared your pointer without referencing something.
So try to initialize the pointer like this:
// Initialize with the null pointer:
int* i = nullptr;
// Or initialize with a valid address:
int ival = 5;
int* ipoint = &ival ;
Anyways, you should think of using references or smart pointers instead of raw pointers.

Related

Vector of structures is causing file.exe to stop working

I'm trying to create a dynamic array of pointers to structure objects. I have done this before, but never really understood it, so I'm lost now that it's failing.
My code is:
struct object {
char* alias;
char* mapInfo;
char* binaryData;
};
class ATP
{
public:
ATP();
std::vector<std::shared_ptr<object>> objects;
};
This compiles fine, but when I try to run it it says
"ATPEditor.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
I'm not trying to use anything like a push_back yet, I'm just trying to create the array.
Does anyone know why this is failing? Or if there is somewhere else I might have made a mistake?
EDIT: When copying the rest of my code into this window, I noticed that I had mistyped the constructor. Once I fixed it the problem went away. Thanks.

SEGFAULT when passing QString by refernce to library function

I've been fighting with this all day long and I've tried passing a QString, a std::string, and a char* in many many different fashions, but if I pass it so that I can modify the parameter's value inside the library function then it SEGFAULTs. If I copy the library function, line for line, into the main app, I can pass references all day long as params and change their values inside the functions.
Here is the stripped down version of my function inside the library.
I have literally removed all code except for this line.
MySQLLib::ExecuteQuery(const QString& query, QString& results)
{
results = "Changed the value of this parameter.";
}
Here is the calling code from the main application.
bmdbTest is an instance of the above MySQLLib class...
All the other code in my library and application works. It just won't let me pass references to ANYTHING to my library.
MySQLProj::pbExecuteQuery_Click()
{
QString x = "Hello.";
bmdbTest->ExecuteQuery("SELECT ttid from test_table", x);
ui_MySQLProj1.textEdit->setText(x);
}
It SEGFAULTs on the bmdbTest->ExecuteQuery call.
I've even tried a simple int& as a parameter with no success.
I can however pass params as const QString& without issue. I just can't modify the param's value that way.
EDIT: I just figured it out. Thank you to "paxdiablo" for suggesting I check my variables for null or invalid pointers. I was really tired last night and I can't believe I missed this.
I just found the problem and I feel like a complete idiot. You mentioned about bmdbTest being null or invalid. The value of bmdbTest was fine as all my other functions worked fine, but when I was calling ExecuteQuery() I was passing the query string from the value in a QLineEdit from my GUI window like this.
bmdbTest->ExecuteQuery(leQuery->text(), resultString);
The leQuery->Text() was actually the problem as I must access leQuery like this.
bmdbTest->ExecuteQuery(ui_MySQLProj1.leQuery->text(), resultString);
You may want to check the value of bmdbTest itself. It may be null or an invalid pointer.
That seems to be indicated by the fact it's faulting on that line. If there were something suspect about the parameters, I would expect it to fault within the ExecuteQuery function.
You should be able to find out exactly where the crash is by putting suitable debug statements (with flushing) on either side of the results = ... and bmdbTest->ExecuteQuery(...) lines (or use a debugger if you have one).

CUDA/C++: Passing __device__ pointers in C++ code

I am developing a Windows 64-bit application that will manage concurrent execution of different CUDA-algorithms on several GPUs.
My design requires a way of passing pointers to device memory
around c++ code. (E.g. remember them as members in my c++ objects).
I know that it is impossible to declare class members with __device__ qualifiers.
However I couldn't find a definite answer whether assigning __device__ pointer to a normal C pointer and then using the latter works. In other words: Is the following code valid?
__device__ float *ptr;
cudaMalloc(&ptr, size);
float *ptr2 = ptr
some_kernel<<<1,1>>>(ptr2);
For me it compiled and behaved correctly but I would like to know whether it is guaranteed to be correct.
No, that code isn't strictly valid. While it might work on the host side (more or less by accident), if you tried to dereference ptr directly from device code, you would find it would have an invalid value.
The correct way to do what your code implies would be like this:
__device__ float *ptr;
__global__ void some_kernel()
{
float val = ptr[threadIdx.x];
....
}
float *ptr2;
cudaMalloc(&ptr2, size);
cudaMemcpyToSymbol("ptr", ptr2, sizeof(float *));
some_kernel<<<1,1>>>();
for CUDA 4.x or newer, change the cudaMemcpyToSymbol to:
cudaMemcpyToSymbol(ptr, ptr2, sizeof(float *));
If the static device symbol ptr is really superfluous, you can just to something like this:
float *ptr2;
cudaMalloc(&ptr2, size);
some_kernel<<<1,1>>>(ptr2);
But I suspect that what you are probably looking for is something like the thrust library device_ptr class, which is a nice abstraction wrapping the naked device pointer and makes it absolutely clear in code what is in device memory and what is in host memory.

Qt: function returns object, putting it into a pointer

Hopefully this isn't too stupid but I want to make sure I'm doing this right.
Some Qt functions return Qt objects as values, but we may want to store them in a pointer somewhere. For example, in QDomDocument, the function documentElement returns a QDomElement, not a pointer to it. Now, as a member of my class I have:
QDomElement *listRootElement;
In a function that sets things up I am using this:
listRootElement = new QDomElement;
*listRootElement = mainIndex->documentElement();
(mainIndex is a QDomDocument.)
This seems to work, but I just want to make sure I'm doing it right and that nothing will come back to bite me.
It would be very similar for some of the image functions where a QPixmap might be returned, and I want to maintain pointers to QPixMap's.
Thanks for any comments!
Assuming that you want to store a pointer to a QDomElement for some reason, and assuming that you aware of the potential pitfalls with pointers (like, two pointers might point to the same object):
The only thing to keep in mind is that the popular 'parent takes care of deleting children' system which Qt uses is only available for QObject (sub-)classes. So when new'ing a QString or a QDomElement or something like that, keep in mind that you do have to delete it yourself, too.
I'm guessing, but I think this:
listRootElement = new QDomElement(mainIndex->documentElement());
...may allow the compiler to optimise better (see this question for some reasoning).
You're overwriting the initially allocated object:
QDomElement *listRootElement; // undefined ptr value, I'd prefer null or new right away
listRootElement = new QDomElement;
*listRootElement = mainIndex->documentElement();
You're essentially doing:
int *x = new int(42);
*x = 47;
This works because both QDomElement and int implements the assignment operator (=).
Note that there's no need to delete anything, as the returned temporary is copied into your newly allocated object.

Pointer to Pointer Managed C++

I have an old C library with a function that takes a void**:
oldFunction(void** pStuff);
I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):
oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
This gives me the following error from Visual Studio:
error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'
I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.
Any advice on how to do this?
EDIT: Fixed answer, see below.
Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition of m_pStuff with:
#pragma unmanaged
void* m_pStuff
#pragma managed
This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly.
Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so.
Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:
// TestSol.cpp : main project file.
#include "stdafx.h"
using namespace System;
#pragma unmanaged
void oldFunction(void** pStuff)
{
return;
}
#pragma managed
ref class Test
{
public:
void* m_test;
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
Test^ test = gcnew Test();
void* pStuff = test->m_test;
oldFunction(&pStuff);
test->m_test = pStuff;
return 0;
}
Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs.
Thanks for the advice, the pointer is to an C style abstract structure which I think if I leave that structure exposed to the managed code is going to cause further pain due to its lack of defined structure. So what I think I will do is wrap the C library in C++ and then wrap the C++ wrapper with managed C++, which will prevent exposing those C structures to managed code.

Resources