c++ - error: Cannot access memory at address -


i'm trying return pointer function in derived class, code:

class a

class {   protected:   c c;   public:   virtual void func(){    unsigned char *data;    int size=getdata(data);   } } 

class b

class b : public {  private:  int size; public:  b(const c &_c) { c=_c; };  const int b::getdata(unsigned char *data) const {     data=(unsigned char *)malloc(size);     memcpy(data,c.getmem(),size);     if(!data){         //err     }     return size; } 

class c

class c {  private:   unsigned char *mem;  public:   c(unsigned char *_mem) : mem(_mem);   const unsigned char *getmem() const { return mem; }; } 

main.cpp

c c(...); b *b=new b(c); b->func(); 

the error when getdata returns

(this=0x50cdf8, data=0x2 <error: cannot access memory @ address 0x2>, size=32) 

thanks.

in class a, func() worthless because:
1. size not returned caller.
2. pointer data local func , it's contents disappear after end of execution in func().

you don't need return const int function. function return copy of variables, constant (copies).

don't use malloc in c++, use operator new. malloc function not call constructors objects.

don't use new or malloc unless absolutely necessary. usually, dynamic memory containers capacity not known @ compile time; or objects live beyond function or statement block's execution time. if must use dynamic memory, use smart pointer (like boost::shared_ptr).

use std::vector dynamic arrays. works; it's been tested; don't have write own, including memory management.

you passing data value (a copy of pointer). if want modify pointer, pass reference or pass pointer pointer; (what call address of pointer).

example:

void my_function(uint8_t * & p_data) {   p_data = new uint8_t[512]; } 

or

void another_function(unsigned char * * pp_data) {   *pp_data = new unsigned char [1024]; } 

a better solution:

void better_function(std::vector<uint8_t>& data) {   data.reserve(64);   (uint8_t = 0; < 64; ++i)   {     data[i] = i;   } } 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -