首页 > 解决方案 > CUDA C为结构的结构分配GPU内存

问题描述

我用一些像素实现了屏幕表示,可以绘制一个简单的金字塔(通过为屏幕中的每个像素分配一个 RBG 值)。在学习 CUDA C 时,我想重新实现它以在 GPU 中分配这些值,但是为结构结构正确分配内存对我来说很复杂。

我已经在 CPU 上试过了:

#include <stdlib.h>
#include <stdio.h>
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} Pixel;

typedef struct {
    unsigned int width;
    unsigned int height;
    Pixel* pxp ;
} Screen;
Screen* newScreen(int width, int height){
    Screen *sc=malloc(sizeof(Screen));

    sc->width=width;
    sc->height=height;
    sc->pxp=malloc(width*height*sizeof(Pixel));

    return sc;
}
void removeScreen(Screen* sc){
    free(sc->pxp);
    free(sc);
}
void drawPrmd(Screen *sc){
    for(long int i=0;i<sc->height;i++){
        int index=(int) (i*sc->width +sc->width/2);


        for(long int j=index;j>=index-i;j--){
            if((j< (sc->height*sc->width))&&(j>0)){
                sc->pxp[j].r=255;
                sc->pxp[j].b=255;
                sc->pxp[j].g=255;
            }
        }
        for(long int j=index;j<=index+i;j++){
            if((j< (sc->height*sc->width))&&(j>0)){
            sc->pxp[j].r=255;
            sc->pxp[j].b=255;
            sc->pxp[j].g=255;
            }
        }
    }
}
void printScreen(Screen * sc){
    for(int i=0;i<sc->height;i++){
        for(int j=0;j<sc->width;j++){
            printf("(%u) \t",sc->pxp[i*sc->width+j].r);
        }
        printf("\n");
    }
}

int main(){
    Screen *sc1=newScreen(80,80);
    drawPrmd(sc1);
    printScreen(sc1);
    removeScreen(sc1);

}

当试图实现它以在 GPU 上工作时,我在分配 GPU 内存时遇到了问题:

Screen* newScreenGPU(int width, int height){

    Screen *sc;
    if(cudaMalloc((void **) &sc,sizeof(Screen))!=cudaSuccess)
        printf("Error allocating GPU memory for screen \n");

    if(cudaMalloc((void **) sc->pxp,width * height*sizeof(Pixel))!=cudaSuccess)
        printf("Error allocating GPU memory for pixels \n");
    return sc;
}

**它编译顺利,但我得到Segmentation fault (core dumped)了像素的内存分配(第二次分配)。

- 预期:分配内存并为像素分配 RGB 值。-实际结果:分段错误(核心转储)。

标签: ccudadynamic-memory-allocation

解决方案


推荐阅读