A
Atreya, Chaitanya
When u say,Vivek said:Thank you for your reply. But forgive me for my newbie questions
because if you are right I think I've messed up my concepts somewhere.
But from what I understand its only a variable you can declare a
constant right ? Can the memory contents such as the strings in this
case be constant ?
unsigned char *x = malloc(10);
You are allocating 10 bytes of memory for x.
When u say,
strcpy(x, "text");
You are copying some text ("text" in this case) starting
from the memory location pointed to by the variable x.
As you have already allocated enough memory to hold this
string and also because 10 bytes starting from the address
pointed to by the variable x is allocated for this process
on the heap, there is no error or mistake in the pair of
operations.
read on.....
But, when you sayx points to a text string which is constant.
you try to change the constant -> kaboom
Moreover, if thats the case then how is it that when I used "unsigned
char x[] = ..." the program works perfectly. Also what I get is a BUS
Error, what does that mean, exactly, in this context.
unsigned char *x[] = "text";
In this case the string "text", is a compile time constant string,
i.e, the contents of the actual string that is going to be present
inside the variable at run-time is already known in its entirity at
compile-time itself. So the compiler has the right to implement this as
it feels comfortable and efficient with.
The C compiler stores this string in a read-only part of
the process. This means, the variable x will be made to point
to this memory location that is deemed a read-only memory area
by the compiler. But, when you try to change the memory contents
inside this read-only memory location, there is a bus error!
Thank you again,
Vivek
Bye,
../Chaitanya Atreya