Allocating memory inside a function and returning it back
- by user2651062
I want to pass a pointer to my function and allocate the memory to which this pointer points. I've read in other posts that I should pass a double pointer to this function and I did so, but I keep getting segmentation fault:
#include <iostream>
#include <stdlib.h>
using namespace std;
void allocate(unsigned char** t)
{
*t=(unsigned char*)malloc(3*sizeof(unsigned char));
if(*t == NULL)
cout<<"Allcoation failed"<<endl;
else
for(int m=0;m<3;m++)
*(t[m])=0;
}
int main()
{
unsigned char* t;
allocate(&t);
cout<<t[0]<<" "<<t[1]<<endl;
return 0;
}
the result is always this:
Segmentation fault (core dumped)
I don't think that there's anything missing from this code. What could be wrong?