Y
yccheok
Hi, consider the following bug at
#include <stdio.h>
class Drink {
public:
Drink( char *name_ ) : name( name_ ) {}
char *name;
char & get(int i) { return name; }
};
void stir( char &ch ) { ch++; }
int main() {
Drink Martini("Martini");
printf("%c\n", Martini.get(2));
stir(Martini.get(2));
return 0;
}
which will dump out output:
r
Segmentation fault
I was understand that it is because "Martini" is a const string.
Run-time error will occur while trying to modify const string content.
Now, the challenge here is, is there any way to detect this bug during
compile time? Or is there any good programming practice to prevent
this?
My initial thought is that, re-design Drink object to use std::string.
What if the Drink code is copyrighted to others and I does not have
right to modify it? Is there anywhere I can improve it from client code
side (main function)??
Thank you very much!
-cheok
#include <stdio.h>
class Drink {
public:
Drink( char *name_ ) : name( name_ ) {}
char *name;
char & get(int i) { return name; }
};
void stir( char &ch ) { ch++; }
int main() {
Drink Martini("Martini");
printf("%c\n", Martini.get(2));
stir(Martini.get(2));
return 0;
}
which will dump out output:
r
Segmentation fault
I was understand that it is because "Martini" is a const string.
Run-time error will occur while trying to modify const string content.
Now, the challenge here is, is there any way to detect this bug during
compile time? Or is there any good programming practice to prevent
this?
My initial thought is that, re-design Drink object to use std::string.
What if the Drink code is copyrighted to others and I does not have
right to modify it? Is there anywhere I can improve it from client code
side (main function)??
Thank you very much!
-cheok