How to delete Matrixxd def in Eigen in JNI - java-native-interface

Exist the way how can I delete Matrixxd declared? Because when I want to use:
delete
This says error in compile
Eigen::Matrix4d' argument given to 'delete', expected pointer
make.exe: ***
When I want to use:
JNIEXPORT void JNICALL Java_com_jp_algi_CoreC_vector
(JNIEnv *env, jobject clazz, jfloatArray input){
jfloat* flt1 ;
jsize size = env->GetArrayLength(input);
jint i;
jint j=0;
jfloat* out ;
Matrix4d C(400,400);
//compute part
delete C;
And whats the difference between Jdouble and C+ Double? I think there is not one. So the J Datatypes I can use only for the order in the code?

First of all, Matrix4d C(400,400); does not make sense: a Matrix4d is a 4x4 matrix, so it cannot be resized to a 400x400 matrix.
Second, the operator delete is used to free memory allocated by the operator new. In your case the matrix C is created on the stack, and it is C that is responsible to allocate/free the underlying memory.
So assuming you actually want dynamic sized matrices, (i.e., MatrixXd), then you can simply resize it to 0x0 to free the allocated memory:
MatrixXd C(400,400);
// ...
C.resize(0,0);
// reuse C later
If you don't need C later, you can also use blocks:
{
MatrixXd C(400,400);
// ...
}
// At this stage C has been automatically deleted.

Related

Giving the size to an array with a variable

I've been trying to give an array its size through a variable, but it's not working because "must have a constant value".
int processes[] = { 1, 2, 3 };
int n = sizeof processes / sizeof processes[0];
...
findavgTime(processes, n);
-------------------------------------------------
void findavgTime(int processes[], int n, int bt[])
{
int wt[n], tat[n]; //These two vars are giving me the error
}
Am I missing something?
As you've seen, you can declare an array with a non-constant size like this. You could, however allocate it dynamically using new:
int* wt = new int[n];
int* tat = new int[n];
Just don't forget that you need to delete[] these arrays when you're done.
You can allocate it on the heap like how Mureinik said, but you can also allocate it on the stack (as you were trying to do) with alloca() like this:
int* wt = (int*)alloca(n * sizeof(int));
int* tat = (int*)alloca(n * sizeof(int));
free() should not be called as it is allocated on the stack, not the heap.
Some say using alloca() is bad practice because if the call causes a stack overflow, program behavior is undefined. This shouldn't be a problem as long as the array isn't too long.

Is it safe to pass memory allocated using "new" to C libraries?

I know that new delete are incombatible with malloc free.
Does that mean that I should avoid using new for memory that will be used by a C library?
What are things that can go wrong when using new instead of malloc when I will pass the memory to a C library?
void func()
{
int *p = new int(42);
// Should I insist on using malloc for p if this function is a part
// of a C library?
lib_func(p);
}
Memory is memory, and it does not matter how it was allocated.
As long as you're matching new with delete, new[] with delete[] and malloc/calloc with free (also realloc), you're okay.
If you think about it, even C allocates memory in different places, and it works fine --- if a library expects an int, you can allocate it either on the stack, or on the heap (or in some global storage):
int a;
int* b = malloc(sizeof(int));
static int c;
some_func(&a);
some_func(b);
some_func(&c);
Does that mean that I should avoid using new for memory that will be used by a C library?
Not at all. The memory is the same, so if you provide a safe way to deallocate the memory, you can definitely pass that memory to a C library.
int *p = new int(42);
lib_func(p);
delete p;
Here is another example:
extern "C" {
int* make_buffer(size_t sz) {
return new int[sz];
}
void use_buffer(int* buf) {
... // do something
}
void free_buffer(int* buf) {
delete[] buf;
}
}
The code above lets your C code request dynamically allocated memory from your C++ library.
It is memory as any other so it is safe as long as the C library does not free it.
Note that in your example, you can also use memory on stack which has no allocation or deallocation functions:
void func()
{
int p;
lib_func(&p);
}

vs2010 c++ view pointers content by debug

I'm working in Vs2010 c++ with 2D arrays.
I started off with a 1D pointer and used the operation [] as the following:
class CMatrix
{
void clear();
public:
int nRows;
int nCols;
short * MyMat;
CMatrix();
CMatrix(int r,int c);
~CMatrix(void);
void SetMatrix(int r,int c);
short * operator[] (const int row)
{
return MyMat + (row*nCols);
}
};
I don't mind to change to 2D pointer.
However my problem is with debug. Because I'm using pointers I can't see the arrays content.
Are there any another options ?
I prefer not to use vector.
One way is to use use the Memory viewer.
While debugging ( when stoped at a Breakpoint ), goto the menu Debug > Windows > Memory > Memory 1 to get the memory viewer. Then type-in the memory address ( copy paste the value from your pointer ) so that you can view the memory around that area of your program memory.
When you right click on memory viewer you can choose how you want to view the data ( as ANSI , as 4 integers, as 2 byte integers , as floats , bla bla... )
Also you can use the Watch window at the debug time. just use your pointer as an array ( e.g. if your pointer is char * t, the syntax t[0] will give your data pointed by the pointer t
In the QuickWatch window, you can type the name of the pointer variable followed by a comma and the number of array indices you want to view, e.g. MyMat, 10.

How to initialize an array that is part of a struct typedef?

If I have a typedef of a struct
typedef struct
{
char SmType;
char SRes;
float SParm;
float EParm;
WORD Count;
char Flags;
char unused;
GPOINT2 Nodes[];
} GPATH2;
and it contains an uninitialized array, how can I create an instance of this type so that is will hold, say, 4 values in Nodes[]?
Edit: This belongs to an API for a program written in Assembler. I guess as long as the underlying data in memory is the same, an answer changing the struct definition would work, but not if the underlying memory is different. The Assembly Language application is not using this definition .... but .... a C program using it can create GPATH2 elements that the Assembly Language application can "read".
Can I ever resize Nodes[] once I have created an instance of GPATH2?
Note: I would have placed this with a straight C tag, but there is only a C++ tag.
You could use a bastard mix of C and C++ if you really want to:
#include <new>
#include <cstdlib>
#include "definition_of_GPATH2.h"
using namespace std;
int main(void)
{
int i;
/* Allocate raw memory buffer */
void * raw_buffer = calloc(1, sizeof(GPATH2) + 4 * sizeof(GPOINT2));
/* Initialize struct with placement-new */
GPATH2 * path = new (raw_buffer) GPATH2;
path->Count = 4;
for ( i = 0 ; i < 4 ; i++ )
{
path->Nodes[i].x = rand();
path->Nodes[i].y = rand();
}
/* Resize raw buffer */
raw_buffer = realloc(raw_buffer, sizeof(GPATH2) + 8 * sizeof(GPOINT2));
/* 'path' still points to the old buffer that might have been free'd
* by realloc, so it has to be re-initialized
* realloc copies old memory contents, so I am not certain this would
* work with a proper object that actaully does something in the
* constructor
*/
path = new (raw_buffer) GPATH2;
/* now we can write more elements of array */
path->Count = 5;
path->Nodes[4].x = rand();
path->Nodes[4].y = rand();
/* Because this is allocated with malloc/realloc, free it with free
* rather than delete.
* If 'path' was a proper object rather than a struct, you should
* call the destructor manually first.
*/
free(raw_buffer);
return 0;
}
Granted, it's not idiomatic C++ as others have observed, but if the struct is part of legacy code it might be the most straightforward option.
Correctness of the above sample program has only been checked with valgrind using dummy definitions of the structs, your mileage may vary.
If it is fixed size write:
typedef struct
{
char SmType;
char SRes;
float SParm;
float EParm;
WORD Count;
char Flags;
char unused;
GPOINT2 Nodes[4];
} GPATH2;
if not fixed then change declaration to
GPOINT2* Nodes;
after creation or in constructor do
Nodes = new GPOINT2[size];
if you want to resize it you should use vector<GPOINT2>, because you can't resize array, only create new one. If you decide to do it, don't forget to delete previous one.
also typedef is not needed in c++, you can write
struct GPATH2
{
char SmType;
char SRes;
float SParm;
float EParm;
WORD Count;
char Flags;
char unused;
GPOINT2 Nodes[4];
};
This appears to be a C99 idiom known as the "struct hack". You cannot (in standard C99; some compilers have an extension that allows it) declare a variable with this type, but you can declare pointers to it. You have to allocate objects of this type with malloc, providing extra space for the appropriate number of array elements. If nothing holds a pointer to an array element, you can resize the array with realloc.
Code that needs to be backward compatible with C89 needs to use
GPOINT2 Nodes[1];
as the last member, and take note of this when allocating.
This is very much not idiomatic C++ -- note for instance that you would have to jump through several extra hoops to make new and delete usable -- although I have seen it done. Idiomatic C++ would use vector<GPOINT2> as the last member of the struct.
Arrays of unknown size are not valid as C++ data members. They are valid in C99, and your compiler may be mixing C99 support with C++.
What you can do in C++ is 1) give it a size, 2) use a vector or another container, or 3) ditch both automatic (local variable) and normal dynamic storage in order to control allocation explicitly. The third is particularly cumbersome in C++, especially with non-POD, but possible; example:
struct A {
int const size;
char data[1];
~A() {
// if data was of non-POD type, we'd destruct data[1] to data[size-1] here
}
static auto_ptr<A> create(int size) {
// because new is used, auto_ptr's use of delete is fine
// consider another smart pointer type that allows specifying a deleter
A *p = ::operator new(sizeof(A) + (size - 1) * sizeof(char));
try { // not necessary in our case, but is if A's ctor can throw
new(p) A(size);
}
catch (...) {
::operator delete(p);
throw;
}
return auto_ptr<A>(p);
}
private:
A(int size) : size (size) {
// if data was of non-POD type, we'd construct here, being very careful
// of exception safety
}
A(A const &other); // be careful if you define these,
A& operator=(A const &other); // but it likely makes sense to forbid them
void* operator new(size_t size); // doesn't prevent all erroneous uses,
void* operator new[](size_t size); // but this is a start
};
Note you cannot trust sizeof(A) any where else in the code, and using an array of size 1 guarantees alignment (matters when the type isn't char).
This type of structure is not trivially useable on the stack, you'll have to malloc it. the significant thing to know is that sizeof(GPATH2) doesn't include the trailing array. so to create one, you'd do something like this:
GPATH2 *somePath;
size_t numPoints;
numPoints = 4;
somePath = malloc(sizeof(GPATH2) + numPoints*sizeof(GPOINT2));
I'm guessing GPATH2.Count is the number of elements in the Nodes array, so if it's up to you to initialize that, be sure and set somePath->Count = numPoints; at some point. If I'm mistaken, and the convention used is to null terminate the array, then you would do things just a little different:
somePath = malloc(sizeof(GPATH2) + (numPoints+1)*sizeof(GPOINT2));
somePath->Nodes[numPoints] = Some_Sentinel_Value;
make darn sure you know which convention the library uses.
As other folks have mentioned, realloc() can be used to resize the struct, but it will invalidate old pointers to the struct, so make sure you aren't keeping extra copies of it (like passing it to the library).

Overloading delete and retrieving size?

I am currently writing a small custom memory Allocator in C++, and want to use it together with operator overloading of new/ delete. Anyways, my memory Allocator basically checks if the requested memory is over a certain threshold, and if so uses malloc to allocate the requested memory chunk. Otherwise the memory will be provided by some fixedPool allocators. that generally works, but for my deallocation function looks like this:
void MemoryManager::deallocate(void * _ptr, size_t _size){
if(_size > heapThreshold)
deallocHeap(_ptr);
else
deallocFixedPool(_ptr, _size);
}
So I need to provide the size of the chunk pointed to, to deallocate from the right place.
Now the problem is that the delete keyword does not provide any hint on the size of the deleted chunk, so I would need something like this:
void operator delete(void * _ptr, size_t _size){
MemoryManager::deallocate(_ptr, _size);
}
But as far as I can see, there is no way to determine the size inside the delete operator.- If I want to keep things the way it is right now, would I have to save the size of the memory chunks myself?
allocate more memory than neccessary and store the size information there. That's what your system allocator probably does already. Something like this (demonstrate with malloc for simplicity):
void *allocate(size_t size) {
size_t *p = malloc(size + sizeof(size_t));
p[0] = size; // store the size in the first few bytes
return (void*)(&p[1]); // return the memory just after the size we stored
}
void deallocate(void *ptr) {
size_t *p = (size_t*)ptr; // make the pointer the right type
size_t size = p[-1]; // get the data we stored at the beginning of this block
// do what you need with size here...
void *p2 = (void*)(&p[-1]); // get a pointer to the memory we originally really allocated
free(p2); // free it
}
You could keep a map of memory address to size for your pool-allocated memory. When you delete, check if the pointer is in the map, if it is delete that size, if it isn't call regular delete.
For class type, C++ already supports it directly. For nonclass types, you need to store the size manually like the other solution shows.
struct MyClass {
void operator delete(void *p, size_t size) {
MemoryManager::deallocate(p, size);
}
};
As of C++14 the Standard supports the second size parameter in the global delete allocation function. So want you want to do is possible natively now.
http://en.cppreference.com/w/cpp/memory/new/operator_delete