Am 08.11.15 um 08:45 schrieb Marko Rauhamaa:
Grant Edwards <invalid@invalid.invalid>:

On 2015-11-07, Marko Rauhamaa <ma...@pacujo.net> wrote:
"const" is a very ineffective tool that clutters the code and forces
you to sprinkle type casts around your code.

But it allows the compiler to warn you if you pass a pointer to a
read-only data to a function that expects a pointer to writable data.

Unfortunately, it doesn't:

========================================================================
#include <stdio.h>
#include <string.h>

int main()
{
     const char name[] = "Tom";
     char *p = strstr(name, "Tom");
     strcpy(p, "Bob");
     printf("name = %s\n", name);
     return 0;
}
========================================================================

     $ cc -o prog prog.c
     $ ./prog
     Bob

No warning.


That is strange. In C, I can see thet problem here, because it is impossible to define a const correct strstr. But in C++ I have expected that according to the overload, the const version of strstr would be selected (http://www.cplusplus.com/reference/cstring/strstr/ ) . Still:

apfelkiste:Tests chris$ cat prog.cpp
#include <cstdio>
#include <cstring>

int main()
{
    const char name[] = "Tom";
    char *p = strstr(name, "Tom"); // this line should be an error
    strcpy(p, "Bob");
    printf("name = %s\n", name);
    return 0;
}

apfelkiste:Tests chris$ g++ -Wall prog.cpp
apfelkiste:Tests chris$ ./a.out
Bus error: 10

It segfaults because on OSX, const can be stored in write-only memory.

apfelkiste:Tests chris$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin12.6.0
Thread model: posix


        Christian
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to