Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory allocation issue

My code is like below:

#include <string.h>
int main()
{
    int ii = 123;
    char str[7] = "";
    strcpy(str,"123456");
    return 0;
}

I run this in VS2010, the memory is like below

enter image description here

I am curious what the cc in the memory used for? And how the number of cc is calculated?

like image 971
2power10 Avatar asked Mar 04 '12 03:03

2power10


People also ask

What happens if you don't allocate memory in C?

If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory. This can lead to program crashing.

How does C allocate memory?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

Does C automatically allocate memory?

3.2. 1 Memory Allocation in C Programs The space is allocated once, when your program is started (part of the exec operation), and is never freed. Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable.


2 Answers

When compile for "Debug" in Visual Studio, the cc's are often used to fill up uninitialized memory. That way it's more obvious when you access uninitialized memory.

For example, if you try to dereference an uninitialized pointer, you'll likely get something like:

Access Violation accessing 0xcccccccc

or something like that.

enter image description here

like image 92
Mysticial Avatar answered Oct 23 '22 03:10

Mysticial


When you access the uninitialised memory space, VC2010 will always warn you that you have accessed some address containing 0xcccccccc,

0xcc is the value used by the compiler (in a debug build) to fill up the uninitialized memory.

like image 28
CodingCat Avatar answered Oct 23 '22 02:10

CodingCat