c - NDK - 扩展类并使用指向数组的指针会导致段错误

标签 c pointers crash android-ndk

//我的结构/类

class ImgObj{
public:
    unsigned int *textu; //image
}; 

//我的具有基本功能的通用对象

class Aobj {
  protected:
    ImgObj *_obj;    
  public:

    Aobj();
    virtual ~Aobj();

    ImgObj *getB(int p);
    void add(unsigned int *texture);
};

//Here a create an array of that structure

void Aobj::setFrameCount(int q) {
    _obj = new ImgObj[q];
}

//Adding it

void Aobj::add(unsigned int *texture, int size)
{
counter++;   (counter is 0, I didn't specify this but it is there)
_obj[counter-1].textu = (unsigned int *)malloc(size);
_obj[counter-1].textu = texture;
}


 // Getting back the buffer 

ImgObj *Aobj::getB(int p) {
return &_obj[p];
}


//Extending the main object with some other functions which are not present here

class Background : public Aobj {
public:
    Background();
    virtual ~Background();

};

//---------------------------------

//我的主要测试 //我基本上是在尝试分配图像,并在循环中第二次分配之后 //崩溃了

Main::Main()
{
    // image bytes 11704 -> 77w * 38h * 4


            unsigned int *texture = new unsigned int[11704];  //an example
            //Now imagine I'm filling this array with an image...
            int size = 11704;

            Background *background = new Background;

            background->setFrameCount(1);
            background->add(texture, size);


            unsigned int *testtex; //testing

            while(true)
            {

             testtex = background->getB(0)->textu;  

             } 
            // When using this it crashes (the first time works fine, the second time crash)
     }

最佳答案

_obj[counter-1].textu = (unsigned int *)malloc(size);
_obj[counter-1].textu = texture;

第一行将分配大小为 size 的内存:size 是什么? 第二行将覆盖指向新分配内存的指针并替换该指针:您可能想要复制 texture 指向的内存内容。

关于c - NDK - 扩展类并使用指向数组的指针会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466427/

相关文章:

c - 如何防止网络端口在程序崩溃时保持打开状态

c - 管道化读取指令

c - 如何在我的答案中获得乘号(质因数分解)

c++ - 调整 char 数组的大小并不总是有效

crash - 使用断点时 gdb 崩溃

Android 原生崩溃

c++ - C/C++ 预处理器中宽字符串文字的宏参数字符串化

c - C 中的 malloc() 函数

c# - 将 C 中的指针转换为 C#

c++ - 指向释放变量的指针更改地址