Ulrich Drepper (udrepper) wrote,

More array fun

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.

Tags: programming
  • Post a new comment

    Error

    Comments allowed for friends only

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded  

  • 0 comments