Agile Zone is brought to you in partnership with:

Ayende Rahien is working for Hibernating Rhinos LTD, a Israeli based company producing developer productivity tools for OLTP applications such as NHibernate Profiler (nhprof.com), Linq to SQL Profiler(l2sprof.com), Entity Framework Profiler (efprof.com) and more. Ayende is a DZone MVB and is not an employee of DZone and has posted 434 posts at DZone. You can read more from them at their website. View Full User Profile

Challenge: Spot the Bug

09.27.2013
| 2851 views |
  • submit to reddit

Speaking of unfair interview questions, this would be a pretty evil one.

public MemoryMapPager(string file, FlushMode flushMode = FlushMode.Full)
{
     _flushMode = flushMode;
     var fileInfo = new FileInfo(file);
     if (fileInfo.Exists == false || file.Length == 0)
     {
          _allocatedPages = 0;
          fileInfo.Create().Close();
     }
     else
     {
          _allocatedPages = file.Length / PageSize;
     }
     _fileStream = fileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
}

Can you see the bug? How would you fix it?



Published at DZone with permission of Ayende Rahien, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Little Freaky replied on Fri, 2013/09/27 - 2:31am

I would guess the line

_allocatedPages = file.Length / PageSize;

is wrong, as it uses the length of the filename instead of the length of the file content. But I also don't quite understand the reason behind the expression

if (fileInfo.Exists == false || file.Length == 0)

If here the file.Length is also used by mistake (instead of fileInfo.Length) then I don't see why it is used at all in this expression: The file exists and the else branch would correctly set _allocatedPages to 0. If file.Length is used correctly here, then wouldn't fileInfo.Exists already return false (as no file with an empty name can exist)? And what would fileInfo.Create().Close() do if the filename is indeed empty?

I may have to clarify that I am not a C# programmer, so I don't know the API.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.