protect my char* from outside

P

pembed2003

Hi,
I have the following:

#inclue<stdlib.h>

struct person{
public:
person(){name = malloc(6); strcpy(name,"peter");}
~person(){free(name);}
const char* getName(){return name;}
private:
char* name;
};

int main(int argc,char** argv){
person p;
char* s = (char*)p.getName();
s[0] = 'f';
std::cout<<p.getName()<<std::endl;
return 0;
}

The above prints:

feter

What I want to do is allow my getName() function to return the name of
person but don't allow the caller to modify the name. Any idea?

I can do:

char* person::getName(){
char* s = malloc(strlen(name) + 1);
strpcy(s,name);
return s;
}

But this approach has 2 drawback:

1. Everytime the getName() function is called, a copy of name has to
be made
2. The caller has to remember to free s

Is ther any other solution?

Thanks!
 
B

Ben Pfaff

struct person{
public:
person(){name = malloc(6); strcpy(name,"peter");}
~person(){free(name);}
const char* getName(){return name;}
private:
char* name;
};

Please don't post C++ to comp.lang.c.
 
M

Martin Ambuhl

pembed2003 said:
Hi,
I have the following:

#inclue<stdlib.h>

struct person{
public:
person(){name = malloc(6); strcpy(name,"peter");}
~person(){free(name);}

Please don't pollute comp.lang.c with obfuscated illegal code. Perhaps
comp.lang.c++ knows something about this silliness.
 
R

Régis Troadec

"pembed2003" <[email protected]> a écrit dans le message de

My opinion is that learning C and C++ together and then mix them unproperly
is like practising scubadiving without fins and with polluted air in the
bottle. ;)

Regis
 
P

pembed2003

Ben Pfaff said:
Please don't post C++ to comp.lang.c.

Hi Ben,
If I know this is C++ in the first place, I definitely won't post it
here and waste your time. Because I am new to both C and C++, I didn't
really know my code is not C. Sorry about that! Can you tell me why it
is not valid C so I can fix it and repost it again?

Thanks!
 
J

Joona I Palaste

Hi Ben,
If I know this is C++ in the first place, I definitely won't post it
here and waste your time. Because I am new to both C and C++, I didn't
really know my code is not C. Sorry about that! Can you tell me why it
is not valid C so I can fix it and repost it again?

The above code makes such heavy use of C++-only concepts that it's
practically impossible to "fix" it into C. "Public" and "private"
members, constructors, destructors, for example, are things that only
exist in C++. To make the above code C would pretty much require
implementing your own C++ compiler in C.
 

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
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top