Click here to Skip to main content
15,891,316 members
Articles / General Programming

A Study on Corruption

Rate me:
Please Sign up or sign in to vote.
4.96/5 (17 votes)
30 Jan 2012CPOL5 min read 39.5K   229   28  
Do you believe that memory corruption will generate an immediate, repeatable crash? Some programmers actually do...
#include "stdafx.h"


void OverflowMyBuffer(char *szTest)
{
    // Copy a string of size 13 into a buffer of unknown size. We'll, I'm cheating: I know its size, it's 3 bytes...
    strcpy(szTest, "Hello, world!");  
}
                       
void test ()
{
    const char format[] = "* * * * * nine = %d, eight = %d, seven = %d, szSmallBuffer = '%s'\n";
	// Const everywhere: this cannot change, right? The compiler would tell us, wouldn't it? Well, the contents of this array will be corrupted by a buffer overflow. Stay tuned...
    const int const arr[3] = { 9, 8, 7 };  
    char szSmallBuffer[3];
	// The buffer has no room for the ending zero, but VC++ doesn't seem to mind... 
    strcpy(szSmallBuffer, "abc"); 
	// The next line prints * * * * * nine = 9, eight = 8, seven = 7, szSmallBuffer = 'abc'; not bad. The ending zero after 'abc' has disappeared.
    printf(format, arr[0], arr[1], arr[2], szSmallBuffer); 
    OverflowMyBuffer(szSmallBuffer);
	// The next line prints * * * * * nine = 1998597231, eight = 1684828783, seven = 33, szSmallBuffer = 'Hello, world!'
	// 33 is the ANSI code for '!'; suspicion arises...  
    printf(format, arr[0], arr[1], arr[2], szSmallBuffer); 
	// The next line prints: arr as a string: 'o, world!'
    printf("arr as a string: '%s'\n", arr); 
}

int _tmain(int argc, _TCHAR* argv[])
{
    printf("\n-----\nIn main, before test()\n-----\n");
    test();
    printf("\n-----\nIn main, after test()\n-----\n");
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Israel Israel
Pablo writes code for a living, in C++, C#, and SQL.

To make all that work easier, he uses some C++ libraries: STL, ATL & WTL (to write Windows applications), and code generation.

Pablo was born in 1963, got married in 1998, and is the proud father of two wonderful girls.

Favorite quotes:
"Accident: An inevitable occurrence due to the action of immutable natural laws." (Ambrose Bierce, "The Devil's Dictionary", published in several newspapers between 1881 and 1906).
"You are to act in the light of experience as guided by intelligence" (Rex Stout, "In the Best Families", 1950).

Comments and Discussions