I have to work and create often matrices(I have to use pointers) so I made a function in C++ to allocate space for them and also make sure that the last value is set to NULL.
The application drops this error(glibc detected: memory curruption) in a specific case. Here is the code:
template<typename T> T *allocate(int size) {
T *temp = new T[size];
temp[size] = (T) NULL;
return temp;
}
This works:
unsigned char *tmp = allocate <unsigned char> (10);
But this one drops the error:
unsigned char **tmp = allocate <unsigned char *> (10);
That would be the equivalent of:
unsigned char **tmp = new unsigned char *[10];
tmp[10] = (unsigned char *) NULL;
Which is good. Why would it drop me this error?
Update: Thanks for the responses. I am so blind. That’s one bug. But the problem of the crash was from another part of the code but also because I was adding NULL outside the allocated space of the array.
You can’t do this:
Size in this case is indexing the memory position AFTER the last one you allocated, change it for this: