const string which cause segmentation fault - any way to detect this bug during compile time?

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
 
M

Mike Wahler

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.


It might, it might not. The behavior is undefined.
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?

Sure. Make 'get()' a const member function:

char &get(int i) const { return name; }

Any member function which is not intended to modify
the object's state should be declared const.
My initial thought is that, re-design Drink object to use std::string.

That would allow you to modify the string, yes (unless the
string member were declared const). IMO std::string should
be preferred over 'C-style strings' anyway.
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)??

If you can't modify the code, then all you can do is
'follow the rules' (i.e. don't invoke undefined behavior).

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top