Allocating memory inside a function and returning it back
Posted
by
user2651062
on Programmers
See other posts from Programmers
or by user2651062
Published on 2014-08-19T15:18:15Z
Indexed on
2014/08/19
16:28 UTC
Read the original article
Hit count: 318
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?
© Programmers or respective owner