Bruno Giannotti
Bruno Giannotti

Reputation: 323

SDL_RenderCopy() unexpected behaviour

I'm pretty sure this is not unexpected at all, I'm probably misunderstanding something. I'm trying to call one of the overloaded constructors as such:

SDL_RenderCopy(SDL_Renderer*, SDL_Texture*, SDL_Rect*, SDL_Rect*);

The problem came when I made a static method in a class to retrieve SDL_Rect pointers as such:

static SDL_Rect* getRectangle(rect r) {
    SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
    return &rectangle;
}

So the call is like:

SDL_Rect* r = MyClass::getRectangle(srcRect);
SDL_Rect* r2 = MyClass::getRectangle(destRect);
SDL_RenderCopy(renderer, texture, r, r2);

They are all pointers and are returning coherent values, but for some reason I don't understand, the rectangles that I'm fetching from my class when passed to SDL, are not scaling according to the values of the rectangles. But if I change my static method to return a copy of SDL_Rect, everything works as expected, as such:

static SDL_Rect getRectangle(rect r) {
    SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
    return rectangle;
}

And the call:

SDL_Rect r = Video::getRectangle(srcRect);
SDL_Rect r2 = Video::getRectangle(destRect);

SDL_RenderCopy(renderer, texture, &r, &r2);

Upvotes: 1

Views: 303

Answers (1)

jfMR
jfMR

Reputation: 24738

The problem is in your function getRectangle():

static SDL_Rect* getRectangle(rect r) {
    SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
    return &rectangle;
}

You are returning the address of an object, rectangle, that has automatic storage duration. Therefore, the object doesn't exist after the control returns from the function.


You may want to allocate an SDL_Rect on the heap and return its address instead:

static SDL_Rect* getRectangle(rect r) {
    return new SDL_Rect{ r.x, r.y, r.w, r.h };
}

Upvotes: 3

Related Questions