Sunday, May 29, 2011

Casting away consts in C++

This could be dangerous sometimes. Stroustrup in his book has noted that const variables may be put in read only section of the memory. Hence casting away their consts and modifying them definitely lead to memory access violation. A small example can be like this.

#include <iostream>
#include <string.h>

const char val[] = {"Test1"};

void bad_modify(char* str, char* str2, const size_t len)
memcpy(str, str2, len);

int main()
char* s = "Value";
char* p = const_cast
bad_modify(p, s, 5);

g++ puts the varibale val in readonly section of the memory.
Hence when we cast away const from val and try to modify it, we get segmentation fault.

Comments are always welcome