Memset Segmentation Fault Core Dumped

Memset Segmentation Fault Core Dumped

#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <SDL2/SDL.h>

int main ( int argc, char** argv )
{
const int height = 700;
const int width = 800;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0){
    std::cout << "SDL Failed to initalize" << std::endl;
    return 1;
}
SDL_Window *window = SDL_CreateWindow("Particle Fire Explosion", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);

if (window == NULL){
    SDL_Quit();
    return 1;
}

SDL_Renderer *renderer = SDL_CreateRenderer(window, -1,     SDL_RENDERER_PRESENTVSYNC);
SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, width, height);
if(renderer == NULL){
    std::cout << "COULD NOT CREATE RENDERER" << std::endl;
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 1;

}
if(texture == NULL){
    std::cout << "COULD NOT CREATE TEXTURE" << std::endl;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 1;
}

Uint32 *buffer = new Uint32(width * height);
Uint32 *memsett = new Uint32(width * height * sizeof(Uint32));
memset(buffer, 0xFF, width*height*sizeof(Uint32));

SDL_UpdateTexture(texture, NULL, buffer, width*sizeof(Uint32));
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer,texture, NULL, NULL);
SDL_RenderPresent(renderer);

bool quit = false;
SDL_Event event;

while (quit == false){


    while(SDL_PollEvent(&event)){
        if(event.type == SDL_QUIT){
            quit = true;
        }
    }

}
SDL_DestroyRenderer(renderer);
SDL_DestroyTexture(texture);
delete [] buffer;
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

这是我的代码,我试图在 SDL 中使一个全白的 window 变暗,试图使用 memset 来做到这一点,但它不起作用。该错误说:分段错误核心已转储。当我删除 memset 函数时它消失了,所以我知道 memset 正在使用的内存意味着正在使用内存,所以我该如何更改它?

Uin32 *buffer = new Uint32(width * height) 分配值为 width * height 的单个 Uint32,而不是 width * height Uint32 的数组。然后,您对 memset 的调用会超出该单曲 Uin32 的末尾并写入无主内存。

你想要 [] 而不是 ():

Uint32* buffer = new Uint32[width * height];