MATLAB: Matlab crash after running mex

MATLABMATLAB Builder EXmex

hello my matlab crash after runing mex file, please advise.
the matlab code:
function y = Shash(x,s,k,MM,bb,pass)
z = k/bb*2^bb;
y2 = uint32(Vhash2(uint8(z),s+pass,k,uint32(MM(x+1,:))));
the mex code:
#include "mex.h"
#include "string.h"
#include <math.h>
typedef unsigned int uint32_t;
#ifndef MWSIZE_MIN
typedef unsigned int mwSize;
#endif
uint32_t jenkins_one_at_a_time_hash(unsigned char *key, size_t key_len,uint32_t* Si)
{
unsigned char temp[4];
*temp= *key;
unsigned char new_key[4];// = malloc(key_len);
size_t i;
for( i = 4; i > 0; i--)
{
new_key[i-1] = (unsigned char)((*temp)%2);//(unsigned char)((*(temp))%2);
*temp >>= 1;
}
uint32_t hash = *Si;
for (i = 0; i < 4; i++)
{
hash += new_key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nlhs > 0)
{
mxArray *HMatrix;
int i;
uint32_t *ph;
uint32_t *phTemp;
unsigned char *pd;
uint32_t *mm;
mwSize siz;
pd = (unsigned char *)mxGetData(prhs[0]);
mm= (uint32_t*)mxGetData(prhs[3]);
siz = mxGetElementSize(prhs[3]);
int z = *pd;
uint32_t *res = 0;
int j;
unsigned char *array;
array = (unsigned char *)mxMalloc(z*sizeof(unsigned char));;
for (j = 0; j < z; j++)
{
array[j] = j + 1;
}
pd = array;
siz = 1;
HMatrix = mxCreateNumericMatrix(z, 1, mxUINT32_CLASS, mxREAL);
ph = (uint32_t *)mxGetData(HMatrix);
phTemp = (uint32_t *)mxMalloc(z*sizeof(uint32_t));;
for(i = 0; i < z; ++i)
{
phTemp[i] = jenkins_one_at_a_time_hash(pd + i, (size_t)mxGetData(prhs[2]), (uint32_t*)mxGetData(prhs[1]));
*res = *res + (mm[i]*phTemp[i]);
}
*ph = *res;
plhs[0] = HMatrix;
mxFree(array);
mxFree(phTemp);
}
}
thanks,
snir

Best Answer

uint32_t *res = 0;
That is not a pointer to a value that is 0: that is setting the res pointer to NULL because C defines assigning 0 to a pointer to be equivalent to assigning NULL to it. (C++ has moved away from that.) You are therefore writing into low memory, with undefined results.
If you want a pointer to a 0 then
uint32_t res_data = 0;
uint32_t *res = &res_data;