Object-Oriented Programming

Resource Management

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Automatic Variables

Automatic Variables

  • The constructor is called when the declaration is reached
  • The destructor is called right before the block exits
  • Order of destructor calls is inverse of constructor order

Software View of Resources

  • Memory
  • File handles (e.g., file descriptors)
  • Network connections
  • Locks & semaphores
  • Database connections

Resource must be…

  • Properly allocated
  • Properly initialized before use
  • Properly validated before use
  • Properly deallocated after use

Resource Problems

  • Improper initialization
  • Use when invalid
  • Resource leak (never deallocated)
  • Double free (deallocated more than once)

File Descriptor Resource Leak

  • File descriptor is allocated each time through the loop
  • But file descriptor is not deallocated each time through the loop
  • Will hit a limit that depends on your O.S. environment
  • To view the limit: ulimit -n
  • Note: Some discrepancy on the default limit in Ubuntu (and in srcml/codespaces)
  • Even without a resource leak, you can open too many files simultaneously

Effect of Improperly Used Resources

  • Exceed resource limits
  • Program crash
  • Invalid output
  • Security vulnerabilities

C++ Pointers

  • Pointers to memory
  • Limits on the amount of memory available to a program/process
  • Good pointer usage is not easy to do

C++ Pointer Problems

Avoiding C++ Pointer Problems

  • Behavioral issue
  • Requires complex tools to detect, with lots of false positives
  • Must have a scenario for each usage pattern
  • Good design can prevent the problem from occurring