program crashed by file operation

hi,
I want open a file and read something out but if I close the file then the program crashed and I dont know why. maybe anybody can have a look on the source ?

long CMP3Tag::loadFile(char *Filename)
{

if (Filename != NULL)
{ delete [] m_FileName;
m_FileName = new char (strlen(Filename) + 1);
strncpy (m_FileName, Filename, strlen(Filename));
}
char tmp[256];
memset (tmp, 0, 256);
//dynamic allocate!!!
strncpy(tmp, m_FileName, strlen(m_FileName));

FILE * pFile = NULL;

long length = 0;

pFile = fopen (tmp, "r"/*"rb"*/);
if (pFile == NULL)
perror ("Error opening file");
else
{
fseek ( pFile, 0, SEEK_END );
length = ftell (pFile);

fseek ( pFile, m_cID3v1_Size, SEEK_END );


fgets (buffer/*m_Overlay_mp3Tag.unstructered , m_cID3v1_Size , pFile);
fclose (pFile);//<-- here the program crashe, but why ???

}
return length;
}
strncpy(tmp, m_FileName, strlen(m_FileName));
Wrong. tmp is always 256 characters long, but Filename may be longer.

fgets (buffer/*m_Overlay_mp3Tag.unstructered , m_cID3v1_Size , pFile);
Where does the comment end? How long is buffer?

Whenever a program crashes while trying to allocate or free memory, it suggests memory corruption. Check that you're not overflowing any buffers, or freeing the same pointer twice, and you're not forgetting to initialize anything before trying to use it. That last one actually gave me a very strong headache, once.
hi,
"strncpy(tmp, m_FileName, strlen(m_FileName));"
here I am sure that the buffer is big enough. yes, in the final solution I have to allocate the memory dynamically ;)
to "fgets (buffer/*m_Overlay_mp3Tag.unstructered , m_cID3v1_Size , pFile);"

first I have tried "fgets (m_Overlay_mp3Tag.unstructered , m_cID3v1_Size , pFile);" whereby the size of "m_Overlay_mp3Tag.unstructered" is 128 bytes (m_cID3v1_Size=128, too). I think it is correct, or ?
the "m_Overlay_mp3Tag" is initialized at creation with '0', I have used memset.
The problem is the fclose, at this point the program crashed and I dont know why.

regards
If you're sure those can't be overflowed then you have memory corruption elsewhere. Try running your program through Valgrind.
yes you must have right, because I have copied the content of the procedure in the main part and it works. I have to find the corruption at any other point.

thanks for your idea/help
regards
Topic archived. No new replies allowed.