I have a big program that is causing me access violation when using sdl_rwops. So I decided to create a small program just to test sdl_rwops and it is causing me the same access violation. For what I could see it is being caused because of the fopen_s() part but I could not figure out why. Maybe you guys can find what I am missing. Here is the code:
#include "SDL.h"
#include < stdio.h >
int main(int argc, char *argv[])
{
FILE *file;
SDL_Surface *screen;
SDL_Surface *one;
SDL_Rect rect;
errno_t err;
/* This is the RWops structure we'll be using */
SDL_RWops *rw;
SDL_Init(SDL_INIT_VIDEO);
atexit(SDL_Quit);
screen = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF);
/* Here we get a file pointer to a bitmap */
if ( (err = fopen_s(&file,"penguin.bmp", "r")) != 0)
{
printf("Couldn't load penguin.bmp\n");
exit(1);
}
/* This is where we actually create our RWops structure. Here we're
instructing SDL to get it from the file pointer we just opened */
rw = SDL_RWFromFP(file, 0);
/* SDL_LoadBMP_RW is the RWops version of the old standby,
SDL_LoadBMP. This will get the image from the RWops you passed
in; in this case the file you've opened */
one = SDL_LoadBMP_RW(rw, 0); // This line calls fopen.c and causes the crash
/* Clean up after ourselves */
SDL_FreeRW(rw);
fclose(file);
/* Haphazard way of getting stuff to the screen */
rect.x = rect.y = 20;
rect.w = one -> w;
rect.y = one -> h;
SDL_BlitSurface(one, NULL, screen, &rect);
SDL_Flip(screen);
SDL_Delay(3000);
}
And here is the portion of fopen.c that causes the crash of the program:
errno_t __cdecl _tfopen_s (
FILE ** pfile,
const _TSCHAR *file,
const _TSCHAR *mode)
{
_VALIDATE_RETURN_ERRCODE((pfile != NULL), EINVAL);
*pfile = _tfsopen(file, mode, _SH_SECURE); // This line causes the access violation
if(*pfile != NULL)
return 0;
return errno;
}
The line
one = SDL_LoadBMP_RW(rw, 0);
jumps to fopen.c and the line
*pfile = _tfsopen(file, mode, _SH_SECURE);
in that file makes it crash.
I am using Visual Studio 2012 and the picture is in the same folder as the executable. The SDL.dll and even SDL_image.dll are there too. I found a post in google of the same issue and the person said that when he put the whole path (instead of just penguin.bmp") it would not crash. It did not work for me, crashed anyway. I am starting to think that it may be some SDL initialization issue but I did anything I could find on google and nothing worked. I tryed running in Multi-threaded DLL (/Md), in Multi-threaded Debug Dll (/MDd), tryed running in 64 bits, tyred changing the Subsystem to Windows and to console... everything resulted in the same crash.
The error message is:
Unhandled exception at 0x77888C39 (ntdll.dll) in testrwops.exe: 0xC0000005: Access violation writing location 0x00000014.
Which makes me think of a null pointer. So I even tryed to allocate memory for file and rw with new and malloc but it didnt work also. I pretty much used the same code as this site but maybe it is out of date.
Thanks for any help.