Christian Christmann <pl*****@yahoo. de> writes:
I'm wondering if my small example is not
"dangerous" :
#define SIZE 10
char global[SIZE];
char* globalPtr = global;
int main()
{
char i;
for ( i = 0; i < SIZE; i = i + 1 ) {
(*globalPtr) = i;
globalPtr++;
}
}
I'm initializing the char array 'global' with
integer values (represented by 'i'). But since the
integer data type is 4x larger (4 byte on my machine) than
the char data type, I initialize the char element but at
the same time I overwrite the 3 subsequent char array elements
by the remaining 3 integer bytes. Moreover, when initializing
the last array element, I write 3 bytes beyond the array ranges
which might corrupt some other values stored in memory.
Is this right?
A simple assignment, such as your "(*globalPt r) = i;", simply copies a
value (determined by evaluating the right hand side) to an object
(determined by the left hand side). The expression is converted, if
necessary, to the target type; it will never write any data outside
the target object.
You said elsewhere that you meant i to be an int, not a char. That
just means that the value is converted from int to char. There could
be problems with the conversion if the value is to large to fit in a
char, but the worst thing that can happen is that some
implementation-defined value is assigned to the target (or, in C99,
that an implementation-defined signal is raised); it will never
clobber memory outside the target object. (Any problems occur on the
conversion, not on the assignment.)
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.