fstream

when i run this code it gets compiled successfully but after running gives me an error and closes down abruptly!!!



#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<cstdlib>
#include<iostream.h>
#include<fstream.h>
#include<string.h>

int main(void)
{
fstream file1,file2;
char *str=NULL,ch;
int i=0,j=0;
//clrscr();
free(str);
str = (char*) malloc(sizeof(char*));


i=0;
file1.open("c:/Dev-Cpp/ab/lan1.txt",ios::in) ;
file2.open("c:/Dev-Cpp/ab/lan11.txt",ios::out);
while(file1)
{
file1.get(ch);
str[i]=ch;
if(str[i]=='M' || str[i-1]=='A'&& str[i-1]=='P')
i=i-32;
i++;

}
for(j=0;j<i;j++)
file2<<str[j];
file1.close();
file2.close();
free(str);

}
getch();
return 0;
}


str = (char*) malloc(sizeof(char*)); allocates a block of four bytes (typically).

The while loop will a probably go around more than four times, causing you to overrun your four byte buffer, which corrupts the heap, which puts the program in an indetermate state.
Topic archived. No new replies allowed.