سؤال

I'm making a game in SDL, and I'm using SDL_VideoInfo to get the monitors current resolution.

Example Code: (This may have a few spelling mistakes or wrong names for functions/variable types, i'm writing this right now off my memory).

#include <SDL.h>
#include <iostream>
using namespace std;

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    const SDL_VideoInfo *vInfo = SDL_GetVideoInfo();
    cout << "Moniter Resolution:\n";
    cout << vInfo->current_w << endl << vInfo->current_h << endl;
    delete vInfo;
    return 0;        
}

The first few times I run this, it works fine, then I get the Debug Assertion Failed window popping up on me. I'm not quite sure what it means, but I think it has to do with memory leaks? I'm coming from Java here, so memory leaks and pointers and such is all new to me, so i'm kinda confused.

Anyway, the code works fine when I dont delete vInfo, but after all the C++ books and videos I've looked at, they all send the message that not deleting your pointers is programming sacrilege. So, (apparently) deleting vInfo is my only choice.

So, I think, think I fixed it by doing this, or, at least when I do this there are not Debug Assertion Failed messages: (Once again, doing this from memory, I might have some spelling mistakes or typos that would cause an error, but you should get the point).

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    auto_ptr<const SDL_VideoInfo> vInfo(SDL_GetVideoInfo());
    cout << "Moniter Resolution:\n";
    cout << vInfo->current_w << endl << vInfo->current_h << endl;
    vInfo.release();
    return 0;        
}

Throw it in an auto pointer, and It all works out. Although I'm still not sure if this is fixing the problem; just because I'm not getting an error message doesn't mean that something bad isn't happening.

My question is, why do I have to put vInfo in an auto_ptr to avoid this error, is there a way that I can do this without using an auto_ptr, or do I even have to worry about deleting vInfo at all?

Some people might say that this question is useless as I have fixed the problem, but the question i'm asking is not how to fix this error, it is why I got the problem in the first place, and if my solution can be revised in any way(not having to use an auto_ptr, or not having to delete vInfo at all).

P.S. This error certainly isn't just my computer doing something wierd, I've run the same code on multiple computers and got the same result.

هل كانت مفيدة؟

المحلول

From the documentation:

[SDL_GetVideoInfo()] Returns a read-only pointer to the structure containing the information about the current video hardware.

SDL is managing the pointed-to memory so don't try to delete it. In all likelihood it's returning a pointer to a static structure.

Though even if SDL (a C library) wasn't managing the memory and expected you to clean it up you should never call delete on malloc()'d memory.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top