Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to demonstrate memory error using arrays in C++

I'm trying to think of a method demonstrating a kind of memory error using Arrays and C++, that is hard to detect. The purpose is to motivate the usage of STL vector<> in combination with iterators.

Edit: The accepted answer is the answer i used to explain the advantages / disadvantages. I also used: this

like image 448
Sebastian Dressler Avatar asked May 05 '10 20:05

Sebastian Dressler


People also ask

How to solve memory error in C?

delete s; To avoid mismatched allocation/deallocation, ensure that the right deallocator is called. In C++, new[] is used for memory allocation and delete[] for freeing up. In C, malloc(), calloc() and realloc() functions are used for allocating memory while the free() function is used for freeing up allocated memory.

What is a memory error in C?

Memory errors are particularly easy to make in C and can be very hard to debug. Reactis for C automatically detects memory errors. A memory error occurs whenever a program reads-from or writes-to an invalid address.

How are array in C represented in memory?

Arrays are represented with diagrams that represent their memory use on the computer. These are represented by the square boxes that represent every bit of the memory. We can write the value of the element inside the box.

What are arrays in memory?

A memory array is a linear data structure that stores a collection of similar data types at contiguous locations in a computer's memory. Memory arrays are categorized as one-dimensional arrays and multiple-dimensional arrays. Arrays are among the oldest data structures and are used in almost every computer program.


1 Answers

Improperly pairing new/delete and new[]/delete[].

For example, using:

int *array = new int[5];
delete array;

instead of:

int *array = new int[5];
delete [] array;

And while the c++ standard doesn't allow for it, some compilers support stack allocating an array:

int stack_allocated_buffer[size_at_runtime];

This could be the unintended side effect of scoping rules (e.g constant shadowed by a member variable)... and it works until someone passes 'size_at_runtime' too large and blows out the stack. Then lame errors ensue.

like image 58
Stephen Avatar answered Sep 28 '22 07:09

Stephen