S.E.K.
S.E.K.

Reputation: 177

Allocating memory inside a function and returning it back

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?

Upvotes: 0

Views: 131

Answers (2)

wolfPack88
wolfPack88

Reputation: 4203

Look at this line: *(t[m]) = 0;. Since you have given t[m] precedence, it will look for the m-th pointer to char and dereference that. What you actually want to do is dereference t and find the char m places after that, or (*t)[m]. Making this change causes your code to work perfectly: http://ideone.com/JAWeS2

Upvotes: 2

user1172763
user1172763

Reputation: 306

I think this line is treading where it shouldn't:

*(t[m])=0;

Consider the case where m is 2. That's unallocated memory you're writing to. You've done nothing to claim it from the runtime heap.

You may be thinking of something like this:

t[0][m]=0;

Upvotes: 0

Related Questions