System.AccessViolationException in Visual Studio 2008
// diskbin.cpp : main project file.
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <sys/stat.h>
using n开发者_运维技巧amespace std;
int main( int argc, char *argv[] )
{
//code
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
if(stat("seek.pc.db", &files) ==0 )
sizes=files.st_size;
sizek=sizek/sizeof(int);
sizes=sizes/sizeof(int);
int i,min,max,mid;
int *s=new int[sizes];
int *hit=new int[sizes];
//code
}
When I run this program in Visual Studio 2008, I am not getting any error but when I run the cmd opens and then closes followed by a pop up window which says: "An unhandled exception of type 'System.AccessViolationException' occurred in diskbin.exe Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." What could be the issue? Have I not allocated s and hit properly?
Thanks!
It's crashing because you're using uninitialized variables:
int sizes, sizek;
struct stat files, filek;
ofstream ofs;
if(stat("key.pc.db", &filek) ==0 )
sizek=filek.st_size;
if(stat("seek.pc.db", &files) ==0 )
sizes=files.st_size;
sizek=sizek/sizeof(int);
sizes=sizes/sizeof(int);
if stat() fails, you use an uninitialized sizek. Depending on the uninitialized memory, your next statement will crash:
int *s=new int[sizes];
because sizes
can be negative or a very large number and the new will fail.
Check the error returned by stat(), although it's possible the file key.pc.db
is not found, causing the function to fail.
精彩评论