SDL_FreeSurface()

closed account (ETAkoG1T)
I followed a youtube tutorial, he made a program printing out text to the screen with the library SDL_ttf.h everything works except the line that says,
SDL_FreeSurface(message);
It will compile but at runtime it stops working. (The window that says, the program has stopped working pops up) If I remove the line the program works, but he said that would caus a lot of memory problems, why doesn't the code work with the line? Do I need the line?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "SDL.h"
#include "SDL_image.h"
#include <Iostream>
#include "SDL_ttf.h"

int main(int argc, char* args[])
{
	using namespace std;
	bool running = true;
	//Init SDL
	if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
	{
		running = false;
	}


	TTF_Init();



	SDL_Surface *screen;

	screen = SDL_SetVideoMode(800, 600, 24, SDL_HWSURFACE);

	SDL_WM_SetCaption("SDL tutorial", NULL);

	if(screen == NULL)
	{
		running = false;
	}


	SDL_Event occur;

	TTF_Font *times;

	SDL_Color white = { 255, 0, 255}; // not really white :P

	times = TTF_OpenFont("Times.ttf", 20);

	SDL_Surface *message = TTF_RenderText_Solid(times, "This is my text" , white);

	while(running == true)
	{
		
		SDL_PollEvent(&occur);

		if(occur.type == SDL_QUIT)
		{
			running = false;
		}
		
		SDL_FillRect(screen, NULL, 0);
		
		SDL_BlitSurface(message, NULL, screen, NULL);

		SDL_FreeSurface(message); // How to use this?
		
		SDL_Flip(screen);				

	}

	TTF_Quit();
	//Quit SDL
	SDL_Quit();
	return 0;
}
 
Last edited on
closed account (ETAkoG1T)
The window that pops up looks like this but with the name of my program instead,
http://www.online-tech-tips.com/wp-content/uploads/2010/12/wordhasstoppedworking.png
Take SDL_FreeSurface(message); out of the while loop and probably before TTF_Quit().
closed account (ETAkoG1T)
hmmm, maybe, I don't really think that will help. I need to delete every time I call BlitSurface right?

more info that might help:
The program shows the text for about 2-5 seconds before the program window graying out and showing the message. I can remove the message entirely and the program works. But I have heard that is bad for the memory.
Last edited on
closed account (ETAkoG1T)
I checked how much memory it used, it only used 4000k so I guess it works without SDL_FreeSurface(message);
naraku is right. TTF_RenderText_Solid creates the surface. SDL_FreeSurface deletes it. You don't want to delete it while you are still using it.

Topic archived. No new replies allowed.