473,386 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Constant Data in function copied to stack

Hi,

I've found with my compiler, that when a function contains const
data in a function, that data is first copied to the stack[1].

Given:
/* Example 1 */
char Buffer[1024];

void My_Func(void)
{
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
memcpy(Buffer, TEXT, sizeof(TEXT));
return;
}

My compiler copies the data in TEXT to some memory location,
then passes a pointer to that location to the memcpy routine.

If I move the declaration to outside of the function:
/* Example 2 */
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};

void My_Func(void)
{
memcpy(Buffer, TEXT, sizeof(TEXT));
return;
}
or label it as static (and keep it in the function):
/* Example 3 */
void My_Func(void)
{
static const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
memcpy(Buffer, TEXT, sizeof(TEXT));
return;
}

then the compiler passes a pointer to the text to memcpy,
without making an interim copy.

Here are my questions:
Q1: Is the interim duplication mandated by the C language
specification or is this a problem with my compiler?

Q2: Is the _static_ modifier supposed to have this effect?

Q3: My understanding is that constant data is placed into
a constant area and not copied. Am I wrong?

I'm working on an embedded system and I don't want a duplicate
copy of the data created. In our system, we've replaced
memcpy with memcpy_byte (our proprietary function) and we don't
want the library version invoked, which is what the compiler
does in Example 2.

------
[1] Yes, I know that the standard doesn't require implementations
to have a stack, call it read/write memory if "stack" bothers
you.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #1
3 1728
Thomas Matthews wrote:
I've found with my compiler, that when a function contains const
data in a function, that data is first copied to the stack[1].

Given:
/* Example 1 */
char Buffer[1024];

void My_Func(void)
{
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
This instructs the compiler to create an automatic variable of type
"array of 6 char". If instead of calling "memcpy", you were passed
the address of this function to another function defined elsewhere
then the compiler would have no way of knowing that there is only one
copy of TEXT active at any time, so it would be obliged

#include <stdio.h>

void My_Func(void);
void function(const char *text)
{
static const char *saved;
if (!saved) {
saved = text;
My_Func();
}
else {
printf("Second call: %d %s %s\n", saved == text, saved, text);
}
}

void My_Func(void)
{
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
function(TEXT);
}

int main()
{
My_Func();
return 0;
}

The output of this program is:

Second call: 0 Hello Hello

The second time 'function' is called, the pointers 'saved' and 'text'
each point to a valid, active variable called 'TEXT', one in each
active invocation of 'My_Func'. The C standard requires that these
two variables have distinct addresses, so the compiler is obliged to
create two copies.
memcpy(Buffer, TEXT, sizeof(TEXT));
Since memcpy() is a standard function, the compiler has special
knowledge; it knows that memcpy() doesn't capture the value of the
source pointer and that it doesn't invoke 'My_Func' recursively, so it
could legitimately create only a single, static copy of 'TEXT' as an
optimization. As it happens, that optimization is entirely
unnecessary, because there are at least two ways for the programmer to
indicate that only a single copy is desired. Both involve objects
with static storage duration:

void My_Func(void)
{
const char *TEXT = "Hello";

This creates an unamed static array of char and assigns the address of
the first element to the variable 'TEXT'.

void My_Func(void)
{
static const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};

This creates a named array of char with static storage duration. In
both of these cases there is only one object involved, and there is no
reason for any compiler to make unwanted copies. I think that answers
all of your questions, but just to be clear:
Here are my questions:
Q1: Is the interim duplication mandated by the C language
specification or is this a problem with my compiler?
No. The duplication is mandated unless the compiler can prove that
there is no way for a strictly conforming program to tell whether or
not a copy was made.
Q2: Is the _static_ modifier supposed to have this effect?
Yes.
Q3: My understanding is that constant data is placed into
a constant area and not copied. Am I wrong?


Yes.

Jeremy.
Nov 14 '05 #2
Thomas Matthews wrote:
I've found with my compiler, that when a function contains const
data in a function, that data is first copied to the stack[1].

Given:
/* Example 1 */
char Buffer[1024];

void My_Func(void)
{
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
This instructs the compiler to create an automatic variable of type
"array of 6 char". If instead of calling "memcpy", you were to pass
the address of TEXT to another function defined elsewhere then the
compiler, with no way of knowing that there is only one active copy
accessible at any time, would be obliged to actually allocate a new
variable on each call to the function.

#include <stdio.h>

void My_Func(void);
void function(const char *text)
{
static const char *saved;
if (!saved) {
saved = text;
My_Func();
}
else {
printf("Second call: %d %s %s\n", saved == text, saved, text);
}
}

void My_Func(void)
{
const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};
function(TEXT);
}

int main()
{
My_Func();
return 0;
}

The output of this program is:

Second call: 0 Hello Hello

The second time 'function' is called, the pointers 'saved' and 'text'
each point to a valid, active variable called 'TEXT', one in each
active invocation of 'My_Func'. The C standard requires that these
two variables have distinct addresses, so the compiler is obliged to
create two copies.
memcpy(Buffer, TEXT, sizeof(TEXT));
Since memcpy() is a standard function, the compiler has special
knowledge; it knows that memcpy() doesn't capture the value of the
source pointer and that it doesn't invoke 'My_Func' recursively, so it
could legitimately create only a single, static copy of 'TEXT' as an
optimization. As it happens, that optimization is entirely
unnecessary, because there are at least two ways for the programmer to
indicate that only a single copy is desired. Both involve objects
with static storage duration:

void My_Func(void)
{
const char *TEXT = "Hello";

This creates an unamed static array of char and assigns the address of
the first element to the variable 'TEXT'.

void My_Func(void)
{
static const char TEXT[] = {'H', 'e', 'l', 'l', 'o', '\0'};

This creates a named array of char with static storage duration. In
both of these cases there is only one object involved, and there is no
reason for any compiler to make unwanted copies. I think that answers
all of your questions, but just to be clear:
Here are my questions:
Q1: Is the interim duplication mandated by the C language
specification or is this a problem with my compiler?
No. The duplication is mandated unless the compiler can prove that
there is no way for a strictly conforming program to tell whether or
not a copy was made.
Q2: Is the _static_ modifier supposed to have this effect?
Yes.
Q3: My understanding is that constant data is placed into
a constant area and not copied. Am I wrong?


Yes.

Jeremy.
Nov 14 '05 #3
Thomas Matthews <Th****************************@sbcglobal.net> wrote:

Here are my questions:
Q1: Is the interim duplication mandated by the C language
specification or is this a problem with my compiler?
Neither. The compiler is at liberty to treat such an array as if it
were static (because any attempt to modify it results in undefined
behavior), but is under no obligation to do so, nor would most
programmers expect it to.
Q2: Is the _static_ modifier supposed to have this effect?
Yes. Conceptually, automatic variables are created (and initialized)
each time the containing block is entered and destroyed when the block
is exited; static variables are conceptually created at program startup
and destroyed at program end. Your compiler (like most compilers) is
implementing this concept literally -- allocating space (on the stack)
each time the block is entered and initializing it to the correct
values even though this particular automatic variable is declared const.
Q3: My understanding is that constant data is placed into
a constant area and not copied. Am I wrong?


Yes. Defining an object as const simply indicates that you do not
intend to modify it. It does not oblige the compiler to prevent you
from modifying it or to perform optimizations based on it not being
modifiable.

-Larry Jones

He just doesn't want to face up to the fact that I'll be
the life of every party. -- Calvin
Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: pvinodhkumar | last post by:
The number of elemets of the array, the array bound must be constant expression?Why is this restriction? Vinodh
3
by: Thomas Matthews | last post by:
Hi, I've found with my compiler, that when a function contains const data in a function, that data is first copied to the stack. Given: /* Example 1 */ char Buffer; void My_Func(void)
7
by: Thomas L. | last post by:
Hi all, Does a "NULL constant function" exist in C? I mean: I am searching for a C language constant which would be something like a function but which would be translated by a compiler into...
13
by: ravinderthakur | last post by:
hi all experts, i have a structure with the constant memebers such as one given below: typedef struct { const int cbcode; int cberror; } xtsetplatestaterec;
3
by: Moger | last post by:
This is a two parte 1. What to the performance differnace between a Class and a struct. I have a handler class which has a list containing a lot of instances of a class which purely holds data, All...
11
by: John Friedland | last post by:
My problem: I need to call (from C code) an arbitrary C library function, but I don't know until runtime what the function name is, how many parameters are required, and what the parameters are. I...
7
by: Arpan | last post by:
The .NET Framework 2.0 documentation states that An Object variable always holds a pointer to the data, never the data itself. Now w.r.t. the following ASP.NET code snippet, can someone please...
11
by: Brad Pears | last post by:
I am using a function called "CreateSQLParam" which adds SQL parameters to a collection. The function is shown below... I add a parameter to a collection using the following line code... ...
3
by: jacob navia | last post by:
Abstract: Continuing the discussion about abstract data types, in this discussion group, a string collection data type is presented, patterned after the collection in C# and similar languages...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.