Arn
Arn

Reputation: 600

passing char* back and forth between functions

I have two functions and I'm trying to pass a buffer from one function to the other and have it modify the contents, but I cannot seem to get it to work..here is what i have:

void caller ()
{
    char *  datum;
    populate (&datum);
}

void populate (void * buf)
{
    unsigned char * datump;
    int dtsz;
    getData (datump,dtsz);   // This function puts "001" in datump and dtsz = 4 

    buf = new unsigned char[dtsz];
    memset(datumbuf,0,sizeof(buf));
    memcpy (buf,datump,dtsz);

}

When I debug through everything seems to be exactly like it should be until I get to memcpy. It does not seem like memcpy actually does anything. The reason "datumbuf = new unsigned char[dtsz]" is done is because the "getData()" function returns each time with a different size depending on the data size, hence the size can't be statically assigned.

When I get back to the main "caller()" function, the "datum" contains junk.

Any ideas why this is happening and how it can be fixed?

Thanks

Upvotes: 1

Views: 223

Answers (3)

Roddy
Roddy

Reputation: 68074

Your populate function should just return a pointer. that way everything is much easier.

char * populate()
{
  ...
  buf = new unsigned char[dtsz];
  ...
  return buf;
}

...and then you call it like this:

char * datum = populate()

your current code doesn't work because you're confused between value and reference parameters. You pass datum 'by reference' populate(&datum) but `populate treats it like a value parameter.

Upvotes: 2

RichardPlunkett
RichardPlunkett

Reputation: 2988

That memset line is strange and wrong, sizeof(datumbuf) is the pointer size (4 or 8), not the arrays length. If its 8, it will be writing over other stuff, since the array you describe is only 4 long. Still, I doubt thats your actual error.

Upvotes: 1

erenon
erenon

Reputation: 19128

It's not C++, it's C. Use std::string and forget about such buffers if you're using C++.

You don't modify buf in populate. You don't allocate memory for datump (don't know what getData does).

Upvotes: 2

Related Questions