Search code examples
c++g++memset

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;
}

this Is my code, Im trying to make an all white window in SDL an dim trying to use memset to so this but it is not working. The bug says: Segmentation fault core dumped. It goes away when I remove the memset function, so I know that the memory meaning that memset is using is using memory not free so how do I change this?


Solution

  • Uin32 *buffer = new Uint32(width * height) allocates a single Uint32 with the value width * height, not an array of width * height Uint32s. Your call to memset then writes beyond the end of that single Uin32 and off into unowned memory.

    You want [] instead of ():

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