You have written functions that can potentially lead to memory leaks. Having said that, you have some problems with your code logic.
read1() loads the file into
buffer.
read2() creates a new heap space which
buffer will point to, then loads another file into it. Now, how will
write() know where the
buffer created by
read1() is?
On top of that, do not put your clean up code outside the scope of where you created your resources. This is a very bad practice! Your
read1() function obtains file handle yet this handle is closed after
read1() returns. Obviously, for a small program like yours, it may not be a big deal, but correcting these coding practices early on is much more important.
In any case, your
write() function needs to be re-written. You can actually improve this program by getting rid of the
write() function. The logic will go like this:
1. Create a new file for writing
2. Open first file, read contents, write to the new file, close first file
3. Open second file, read contents, append to the new file, close second file
4. Close new file.
|
Also, your
calcsize() function (if the purpose is to calculate the sum of the number of octets of two files), has incorrect logic/code. Just do something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
/* code is in C */
long calcsize()
{
FILE* fp;
long size = 0;
fp = fopen("file1", "rb");
if (fp != NULL) {
fseek(fp, 0, SEEK_END);
size += ftell(fp);
fclose(fp); /* do not forget this! */
}
fp = fopen("file2", "rb");
if (fp != NULL) {
fseek(fp, 0, SEEK_END);
size += ftell(fp);
fclose(fp); /* do not forget this! */
}
return (size);
}
| |
Some ideas:
1. Do not use heap memory unless necessary. Furthermore, do not dynamically allocate memory based on the size of the file. Consider a case when the file size is 16GiB? Can you guarantee you have enough memory to load it all?
2. If you can work with C++, then do so. And when doing so, follow RAII idiom.