c - 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 值。-实际结果:分段错误(核心转储)。
解决方案
推荐阅读
- java - 我没有收到来自静态类的任何格式化数据
- c# - C# WPF 将 RadioSelect 布尔值保存到 XML 文件(它总是错误的)
- c - 当我编辑linux内核代码时,构建和运行修改后的内核的过程是什么?
- java - 为什么我的程序没有注册无法创建套接字?
- arrays - C - 指针未运行的字符串反转函数
- javascript - lwc中的javascript set.has问题
- firebase - Firebase 云功能初始化不起作用
- python - 除以零 python(列表中的一些条目)
- .net - 是否可以在 mvc 视图上运行 devexpress blazor 组件?
- python-3.x - 蟒蛇 | 旋转矩形并获得新的边界尺寸