Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

open() then close() crash

Status
Not open for further replies.

bonosa

Programmer
May 19, 2004
76
US
On linux if I successfully open a file:

int fd = open("file.txt",O_RDONLY)

check if successful

close(fd)

it crashes at the close()

Why and how to get around this?

Thanks,
Sb

The error msg says free() invalid pointer at some address.
 
You have too little code here to make a sensible guess.
Can you post more?


Trojan.
 
I would always open/close file pointers like this :

Code:
FILE* pFile = fopen("file.txt", "rb");

if (pFile == NULL) {
  // handle error
} 

// do stuff with file handle

// close handle
fclose(pFile);

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Strictly speaking, standard C library fopen() returns file stream pointer, not a file handle. It's a non-standard (from early Unix C) open() returns file handle. Alas, fopen() can't control file sharing...
There is a reason for TrojanWarBlade's question. Where is bad handle check if successful code (fd >= 0 or what else)?..
 
What you have looks correct, so there must be something that you have not included that is causing the error. Some questions:

1. Does this happen for any file, or just a specific file?
2. When you "do stuff", is the stuff getting done properly?
3. After the program terminates, is the file in the state you would expect?
4. Have you tried running it through a debugger to make sure that it is the fclose() statement that is causing the problem?
 
Thanks for answering. Its not fclose() but close() where it crashes (yes -- debugger). SO I went ahead and changed everything to fopen, fclose() and things are fine with this. Why close() crashed is a mystery.

Sb
 
From the man page on close: It is quite possible that errors on a previous write(2) operation are first reported at the final close.

It seems stange that it would complain about free()'ing an invalid pointer if the actual problem had been created with a previous write operation, though. Also mystified.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top