You are viewing udrepper

Ulrich Drepper - More array fun [entries|archive|friends|userinfo]
Ulrich Drepper

[ website | My Website ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

More array fun [Feb. 20th, 2007|03:27 pm]
Previous Entry Add to Memories Share Next Entry
[Tags|]

As a continuation of a previous post, here's another thing I frequently stumble across:

#include <stdio.h>
#include <string.h>
int main(void)
{
  const char s[] = "hello";
  strcpy (s, "bye");
  puts (s);
  return 0;
}

Yes, this code will produce a warning. But it will run. Slowly, since it does not do what the programmer actually meant. s is a dynamic variable. The compiler has to allocate space on the stack (or in TLS) and then copy the string from some static, read-only area into it. This of course is not only slow, uses memory, it also means that the newly created string is NOT read-only. The compiler-generate function prologue has to write to the memory.

Whenever you write code where you define an array in the scope of a function, always stop and think what the semantics should be. For all constant arrays it is almost always correct to have exactly one copy (it cannot be changed). If one copy is needed or OK then don't forget the static:

  static const char s[] = "hello";

If you do this all of a suddenly the code will not only produce a warning, it will also crash at runtime since the string is stored in read-only memory and s is not now really a variable anymore, it's a label for the region in read-only memory.

linkReply