I have a generic problem I suppose.
I`m currently learning C++ and SDL 2.0. SDL provides a function which returns a pointer to a const uint * containing all the keystates.
These are the variables I would like to use:
const Uint8* oldKeyState;
const Uint8* currentKeyState;
In the construction of my input.cpp:
currentKeyState = SDL_GetKeyboardState(&this->length);
oldKeyState = currentKeyState;
And in the Update() method I use:
oldKeyState = currentKeyState;
currentKeyState = SDL_GetKeyboardState(NULL);
However, instead of copying over the last values, all I do is giving a pointer to the oldKeyState, which in turn points to the current keystates..
So how do I go about copying the actual values from the variable's pointer to the current and old keystate? I don't want the pointer in my old keystate since I will not be able to check whether the previous state was UP and the new state is DOWN.
Uint8 oldKeyState[SDL_NUM_SCANCODES];
// ...
memcpy(oldkeystate, currentKeyState, length);
The signature of the function you're calling is
const Uint8* SDL_GetKeyboardState(int* numkeys)
This function has return type const Uint8*, which means it returns a pointer to byte(s). (It does not return a pointer to a pointer.) According to the documentation, this returned pointer actually points to an array of Uint8 (one Uint8 is not big enough to encode the states of all the keys on the keyboard), and the value pointed to by numkeys is overwritten with the length of that array (ie. the number of keys). So to preserve the values in the array, you need to allocate a region of memory the same length as gets stored in this->length, and then copy that memory from SDL's array to your own. Then you'll want to keep a pointer to your own array around for you to continue to use. Because SDL says that the returned pointer to the array is valid for the entire lifetime of the application, you may assume that the length is unchanging, so you don't need to worry about resizing your array, but you should worry about deallocating that memory when you're done with it.
So, I think SDL is mostly a C library.
The const Uint8* returned by SDL_GetKeyboardState is a pointer to the first element in an array in values.
If you want to copy a given state for later reference, you would generally need an array to copy them to, and a for loop to do the copying. eg:
currentKeyState = SDL_GetKeyboardState(&this->length);
savedKeyState = malloc(this->length*sizeof(Uint8));
for(int i=0; i<&this-length, i++) savedKeyState [i] = currentKeyState[i];
Of course that pretty poor code, using a vector might be a better way to go, something like:
currentKeyState = SDL_GetKeyboardState(&this->length);
vector savedKeyState(currentKeyState, currentKeyState+length);
The problem you have here is that you are trying to copy the pointer to a const array, which never changes. As a result, you will see that both pointers go to the same memory address, and you never have two copies of the input state which allows you to check for pressed keys.
Instead, you should use memcpy to copy one array to the other. But in order to do so, you should change the type of oldKeyState to just Uint8*, or else you will get an error for copying into a const array.
So, the code should end up like this:
const Uint8 * currentKeyState;
Uint8 * oldKeyState;
...
//Constructor
currentKeyState = SDL_GetKeyboardState(&this->length);
oldKeyState = new Uint8[this->length];
...
//Input update
memcpy(oldKeyState, currentKeyState, this->length);
SDL_PumpEvents(); //Copy the array before calling PumpEvents()!
currentKeyState = SDL_GetKeyboardState(NULL);
Related
I am resizing an array inside of a method, but since I am using a pointer, the memory address is now incorrect. The diffDataTot pointer is initially created in main(), and then passed into the calculateField() method. The calculateField() method contains new information that needs to be added to diffDataTot, and some old information needs to be removed. I indicated this using the resize() method call.
void calculateField(diffData* diffDataTot){
diffData* filler = (diffData*)malloc(newSize * sizeof(diffData));
filler = resize(newSize, diffDataTot);
free(diffDataTot);
diffDataTot = filler;
free(filler);
}
int main{
diffData* diffDataTot = (diffData*)malloc(sizeof(diffData));
calculateField(diffDataTot);
}
I had to abbreviate this since it is from a full scale simulation that is thousands of lines. However, the issue is that diffDataTot contains the correct information locally inside of the calculateField() method. But the pointer points to a different address in memory than in main(). I could try without using a pointer, but I would like to avoid copying the entire array every time calculateField() is called since it is quite large.
Is there any way for me to pass back the memory of the first element in the array from the calculateField() method?
You need to pass the address of your pointer (pointer on pointer).
void
resizing_func(int **elements,
int *elem_count)
{
//---- get rid of additional indirection ----
int *p=*elements;
int count=*elem_count;
//---- work with local variables ----
// ...
int new_count=2*count; // whatever is needed for the problem
p=realloc(p, new_count*sizeof(int));
// ...
//---- make changes visible in calling context ----
*elements=p;
*elem_count=new_count;
}
void
testing_func(void)
{
int count=100;
int *elements=malloc(count*sizeof(int));
// populate elements
resizing_func(&elements, &count);
// use updated elements and count
}
Depending on the problem, realloc() can be replaced by:
allocate a second buffer,
work with first and second buffer,
free the first buffer and continue with the second,
as in the OP's question.
(by the way, notice that free(filler) will free what was intended to be kept in diffDataTot)
note: as the question is tagged c++, it would have probably been better to use a std::vector and pass it by (non-const) reference; but the provided source code looks like c.
I have a function which retrieves an image from a camera.
This function has a function called GetData() which returns a pointer to the data contained by the Image object created by the camera.
The data pointed to by GetData() is locally initialized.
Currently, I'm copying the data pointed to by GetData element by element using a for loop, but is there a way to copy the data without using a for loop? Or, better yet, avoid copying the data and just copy the pointer address and prevent the local data from being terminated.
Code:
void getImage(unsigned char data[]){
// Get the image in 1d array format
fc::Image rawImage;
//Initializes Image object
error = camera.RetrieveBuffer( &rawImage );
//retrieve and return data
unsigned char *temp = rawImage.GetData(); //returns point to data
for(int i = 0; i < IMG_SIZE; i++){
data[i] = temp[i];
}
}
Called simply with
unsigned char data[size];
getImage(data);
The problem lies in the fact that your data is a local object on the stack. Once your function returns, the fc::Image object (and the data it points to) will be destroyed. I only see three possible ways of getting that data out of the function:
Copy the data to the destination array (like you already do, but maybe using memcpy or something along those lines instead of a naked for loop)
Declare your data member to be static (so it sticks around even after the function returns), then simply set the value of the destination pointer to point to the data by data = rawImage.GetData()
Possibly the best one, if you can do it: change your API! Simply accept a pointer or reference to an fc::Image object and pass that as the argument to camera.RetrieveBuffer so your data lands in the right place to begin with. Or another way would be to return your object by value, and take no arguments in that case.
The second one is kind of funky, since the data would only be valid as long as someone else doesn't call the function again, which is a terrible practice to be honest, so I wouldn't suggest number 2.
Also, this API is pretty bad as it is. What's the guarantee that the passed in pointer will have enough capacity? And also, how does the user know how long is the data they received? You don't return a size value or anything.
EDIT:
There's a more appropriate way of doing number 2. You can do something like this:
#include <unordered_map>
// Ideally this would be wrapped in a class or something. Don't use globals.
std::unordered_map<unsigned char*, fc::Image> images;
void getImage(unsigned char data*){
// Get the image in 1d array format
fc::Image rawImage;
//Initializes Image object
error = camera.RetrieveBuffer( &rawImage );
data = rawImage.getData();
images.insert(std::make_pair(data, move(rawImage)));
}
This uses an unordered_map to keep your local objects alive, so you can safely return pointers into them without having to worry about the lifetime of the objects.
But in this case you will have to create a cleanup function as well:
void destroyImage(unsigned char data*){
images.erase(data);
}
Since the map will keep your objects around forever, you will soon start to fill up memory if you keep getting new images. If you use this method, then your users will have to call destroyImage() as soon as they no longer need the data to avoid leaking memory essentially. This kind of goes agains the memory management guidelines in modern C++ which encourage automatic cleanup, while this would depend on your users to call your cleanup function, which is a little unsafe, but it's still the best you can do in my opinion, since you cannot change your API.
If you can expand your API to include such a function, this is definitely a better way to extend the lifetime of your local objects, rather than marking them static.
I have a c++ function that accepts a Pointer to an array of known size as input and returns an array of size that cannot be determined until the function completes its processing of data. How do I call the c++ function, passing the first array and receive the results as a second array?
I currently do something similar to this:
PYTHON:
def callout(largeListUlonglongs):
cFunc = PyDLL("./cFunction.dll").processNumbers
arrayOfNums = c_ulonglong * len(largeListUlonglongs)
numsArray = arrayOfNums()
for x in xrange(len(largeListUlonglongs)):
numsArray[x] = long(largeListUlonglongs[x])
cFunc.restype = POINTER(c_ulonglong * len(largeListUlonglongs))
returnArray = cFunc(byref(numsArray)).contents
return returnArray
This works so long as the returnArray is of the same size as the numsArray. If it is smaller then the empty elements of the array are filled with 0's. If the returned array is larger than the results get cut off once the array elements are filled.
If it helps, the structure of the returned array contains the size of the returned array as its first element.
Thanks for the help in advance...
Normally it is preferable to get the caller to allocate the buffer. That way the caller is in a position to deallocate it also. However, in this case, only the callee knows how long the buffer needs to be. And so the onus passes to the callee to allocate the buffer.
But that places an extra constraint on the system. Since the callee is allocating the buffer, the caller cannot deallocate it unless they share the same allocator. That can actually be arranged without too much trouble. You can use a shared allocator. There are a few. Your platform appears to be Windows, so for example you can use CoTaskMemAlloc and CoTaskMemFree. Both sides of the interface can call those functions.
The alternative is to keep allocation and deallocation together. The caller must hold on to the pointer that the callee returns. When it has finished with the buffer, usually after copying it into a Python structure, it asks the library to deallocate the memory.
David gave you useful advice on the memory management concerns. I would generally use the simpler strategy of having a function in the library to free the allocated buffer. The onus is on the caller to prevent memory leaks.
To me your question seems to be simply about casting the result to the right pointer type. Since you have the length in index 0, you can set the result type to a long long pointer. Then get the size so you can cast the result to the correct pointer type.
def callout(largeListUlonglongs):
cFunc = PyDLL("./cFunction.dll").processNumbers
cFunc.restype = POINTER(c_ulonglong)
arrayOfNums = c_ulonglong * len(largeListUlonglongs)
numsArray = arrayOfNums(*largeListUlonglongs)
result = cFunc(numsArray)
size = result[0]
returnArray = cast(result, POINTER(c_ulonglong * size))[0]
return returnArray
I haven't cemented my learning of C++ arrays and have forgotten how to do this properly. I've done it with char array before but its not working as well for int array.
I declare a new blank int array:
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Then I assign a pointer to this array:
int *pMyArray = myIntArray
Hopefully thats correct to there.
Then I pass this to another method elsewhere:
anotherMethod(pMyArray)
where I want to assign this pointer to a local variable (this is where I'm really not sure):
anotherMethod(int *pMyArray){
int myLocalArray[];
myLocalArray[0] = *pMyArray;
}
I'm not getting any compilation errors but I'm not sure this is right on a few fronts. Any and all help and advice appreciated with this.
Edit:
I should have said what I am trying to do.
Very simple really, I'd just like to modify a local array from another method.
So I have:
Method 1 would contain:
int myArray1[10] = {0};
Method 2 would be passed the pointer to myArray:
Then some code to modify the variables in the array myArray.
int myIntArray[10];
This is an uninitialized array. It doesn't necessarily contain 0's.
int *pMyArray = myIntArray
Okay, pMyArray points to the first element in myIntArray.
anotherMethod(int *pMyArray){
int myLocalArray[10];
myLocalArray[0] = *pMyArray;
}
This doesn't assign your pointer to anything, it assigns the first value of the local array to the int pointed to by pMyArray, which, remember, was uninitialized. I added the 10 there because you can't have an array of unknown size in C++.
To modify what pMyArray points to, you need to pass it by reference:
anotherMethod(int *& pMyArray)
Also, if you assign it to some values in automatic storage, it will result in undefined behavior, as that memory is no longer valid when the function exits.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
No, this is an array of 10 integers containing values depending on the storage specification.
If created locally, it has random garbage values.
If created globally it is value initialized which is zero initialized for POD.
Besides that your method just assigns the local array with the first vale of the array you pass.
What are you trying to do exactly? I am not sure.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Not correct, it is an array of 10 uninitialized ints.
int *pMyArray = myIntArray
Hopefully thats correct to there.
Not quite correct, pMyArray is a pointer to the 1st element, myIntArray[0].
where I want to assign this pointer to a local variable (this is where
I'm really not sure):
If you really need to assign the pointer, you have to use this code
int *p_myLocalArray;
p_myLocalArray = pMyArray;
There are a few mistakes here.
First, array of zeros (not nulls) is achieved by using the initializer syntax:
int myIntArray[10] = {0};
Second, int myLocalArray[]; has a size of 0. And even if it did have a size of, say, 10, writing myLocalArray[0] = *pMyArray; will assign the first int from pMyArray into mLocalArray, which is not what you meant.
If you want to assign a pointer of the array, then simply:
int *myLocalPointer;
myLocalPointer = pMyArray;
If you want a local copy of the array, you will need to copy it locally, and for that you also need the size and dynamic allocation:
void anotherMethod(int *pMyArray, int size){
int *myLocalArray = (int *)malloc(size * sizeof(int));
memcpy(myLocalArray, pMyArray, size * sizeof(int));
...
free(myLocalArray);
}
void pushSynonyms (string synline, char matrizSinonimos [1024][1024]){
stringstream synstream(synline);
vector<int> synsAux;
int num;
while (synstream >> num) {synsAux.push_back(num);}
int index=0;
while (index<(synsAux.size()-1)){
int primerSinonimo=synsAux[index];
int segundoSinonimo=synsAux[++index];
matrizSinonimos[primerSinonimo][segundoSinonimo]='S';
matrizSinonimos [segundoSinonimo][primerSinonimo]='S';
}
}
and the call..
char matrizSinonimos[1024][1024];
pushSynonyms("1 7", matrizSinonimos)
It's important for me to pass matrizSinonimos by reference.
Edit: took away the & from &matrizSinonimos.
Edit: the runtime error is:
An unhandled win32 exception occurred in program.exe [2488]![alt text][1]
What's wrong with it
The code as you have it there - i can't find a bug. The only problem i spot is that if you provide no number at all, then this part will cause harm:
(synsAux.size()-1)
It will subtract one from 0u . That will wrap around, because size() returns an unsigned integer type. You will end up with a very big value, somewhere around 2^16 or 2^32. You should change the whole while condition to
while ((index+1) < synsAux.size())
You can try looking for a bug around the call side. Often it happens there is a buffer overflow or heap corruption somewhere before that, and the program crashes at a later point in the program as a result of that.
The argument and parameter stuff in it
Concerning the array and how it's passed, i think you do it alright. Although, you still pass the array by value. Maybe you already know it, but i will repeat it. You really pass a pointer to the first element of this array:
char matrizSinonimos[1024][1024];
A 2d array really is an array of arrays. The first lement of that array is an array, and a pointer to it is a pointer to an array. In that case, it is
char (*)[1024]
Even though in the parameter list you said that you accept an array of arrays, the compiler, as always, adjusts that and make it a pointer to the first element of such an array. So in reality, your function has the prototype, after the adjustments of the argument types by the compiler are done:
void pushSynonyms (string synline, char (*matrizSinonimos)[1024]);
Although often suggested, You cannot pass that array as a char**, because the called function needs the size of the inner dimension, to correctly address sub-dimensions at the right offsets. Working with a char** in the called function, and then writing something like matrizSinonimos[0][1], it will try to interpret the first sizeof(char**) characters of that array as a pointer, and will try to dereference a random memory location, then doing that a second time, if it didn't crash in between. Don't do that. It's also not relevant which size you had written in the outer dimension of that array. It rationalized away. Now, it's not really important to pass the array by reference. But if you want to, you have to change the whole thingn to
void pushSynonyms (string synline, char (&matrizSinonimos)[1024][1024]);
Passing by reference does not pass a pointer to the first element: All sizes of all dimensions are preserved, and the array object itself, rather than a value, is passed.
Arrays are passed as pointers - there's no need to do a pass-by-reference to them. If you declare your function to be:
void pushSynonyms(string synline, char matrizSinonimos[][1024]);
Your changes to the array will persist - arrays are never passed by value.
The exception is probably 0xC00000FD, or a stack overflow!
The problem is that you are creating a 1 MB array on the stack, which probably is too big.
try declaring it as:
void pushSynonyms (const string & synline, char *matrizSinonimos[1024] )
I believe that will do what you want to do. The way you have it, as others have said, creates a 1MB array on the stack. Also, changing synline from string to const string & eliminates pushing a full string copy onto the stack.
Also, I'd use some sort of class to encapsulate matrizSinonimos. Something like:
class ms
{
char m_martix[1024][1024];
public:
pushSynonyms( const string & synline );
}
then you don't have to pass it at all.
I'm at a loss for what's wrong with the code above, but if you can't get the array syntax to work, you can always do this:
void pushSynonyms (string synline, char *matrizSinonimos, int rowsize, int colsize )
{
// the code below is equivalent to
// char c = matrizSinonimos[a][b];
char c = matrizSinonimos( a*rowsize + b );
// you could also Assert( a < rowsize && b < colsize );
}
pushSynonyms( "1 7", matrizSinonimos, 1024, 1024 );
You could also replace rowsize and colsize with a #define SYNONYM_ARRAY_DIMENSION 1024 if it's known at compile time, which will make the multiplication step faster.
(edit 1) I forgot to answer your actual question. Well: after you've corrected the code to pass the array in the correct way (no incorrect indirection anymore), it seems most probable to me that you did not check you inputs correctly. You read from a stream, save it into a vector, but you never checked whether all the numbers you get there are actually in the correct range. (end edit 1)
First:
Using raw arrays may not be what you actually want. There are std::vector, or boost::array. The latter one is compile-time fixed-size array like a raw-array, but provides the C++ collection type-defs and methods, which is practical for generic (read: templatized) code.
And, using those classes there may be less confusion about type-safety, pass by reference, by value, or passing a pointer.
Second:
Arrays are passed as pointers, the pointer itself is passed by value.
Third:
You should allocate such big objects on the heap. The overhead of the heap-allocation is in such a case insignificant, and it will reduce the chance of running out of stack-space.
Fourth:
void someFunction(int array[10][10]);
really is:
(edit 2) Thanks to the comments:
void someFunction(int** array);
void someFunction(int (*array)[10]);
Hopefully I didn't screw up elsewhere....
(end edit 2)
The type-information to be a 10x10 array is lost. To get what you've probably meant, you need to write:
void someFunction(int (&array)[10][10]);
This way the compiler can check that on the caller side the array is actually a 10x10 array. You can then call the function like this:
int main() {
int array[10][10] = { 0 };
someFunction(array);
return 0;
}