Re: Possible buffer overruns?
Nephi Immortal <immortalnephi@gmail.com> wrote in
news:44b62e39-e7bd-4b25-b7bf-b0389f365ba6@2g2000yqk.googlegroups.com:
if the code shows below,
int main()
{
const char* A = "0123456789"; // store in stack
const char B[ 10 + 1 ] = "0123456789"; // store in stack
static const char C[] = "0123456789"; // store in data segment
return 0;
}
then do both A and B store 11 characters into stack and C into data
segment?
Why don't you check by yourself? Here is an example program:
#include <iostream>
int main()
{
int stack_top;
const char* A = "0123456789"; // store in stack
const char B[ 10 + 1 ] = "0123456789"; // store in stack
int before_C;
static const char C[] = "0123456789"; // store in data segment
int after_C;
std::cout << "A takes "
<< ( (char*) &stack_top - (char*) &A)
<< " bytes in the stack\n";
std::cout << "B takes "
<< ( (char*) &A - (char*) &B)
<< " bytes in the stack\n";
std::cout << "C takes "
<< ( (char*) &before_C - (char*) &after_C - sizeof(after_C))
<< " bytes in the stack\n";
return 0;
}
In MSVC 32-bit Debug mode (no smart optimizations done by the compiler!)
this prints out:
A takes 4 bytes in the stack
B takes 12 bytes in the stack
C takes 0 bytes in the stack
A is a 4-byte pointer on the stack, the string literal is by itself in
some (read-only) data segment.
B is indeed 11 bytes on stack, 1 extra byte for alignment padding.
C seems to be indeed in a data segment.
If you say data segment, then it should look like this below
void foo( "0123456789" ); // store string in data segment
String literal is in a read-only data segment. A pointer to it is passed
to foo().
// global scope
const char X[] = "0123456789"; // store string in stack?
If it is in global scope, then there is no stack involved. Stack is
related to the actual execution thread; in a multi-threaded program each
thread has its own stack memory, but global variables are visible in all
threads. This already shows they are not on stack.
The string literal itself is placed in a read-only data segment. A copy
may be made for X and placed in a read-write or read-only data segment. I
guess an optimizer is allowed to coalesce these things into one, but not
100% sure.
struct bar
{
static const char N[];
}
const char bar::N[] = "0123456789"; // store string in data segment
This is the same as X I think.
You mentioned that data segment is read only. Can separate data
segment be read/write unless string is non-constant?
Sure, there are read-write data segments as well. Non-const global
variables go there for sure.
hth
Paavo