This question already has answers here:
Char * (pointer) function
(4 answers)
When I change a parameter inside a function, does it change for the caller, too?
(4 answers)
Closed 8 years ago.
I have the following very simple program.
int modify(char * v){
v = "123" ;
return 0;
}
int main (int argc, char** argv){
char *test = new char[10];
modify(test);
std::cout << test;
return 0;
}
I know I can just print out "123", but I deliberately wrote it that way to learn about how pointers work. However, "123" is not printed. How should I correctly pass the pointer?
You have to remember that in C++ arguments are by default passed by value, meaning that in the function you have copies., and modifying a copy will not change the original.
If you want to change the pointer to point to something else you need to pass it by reference. However, in this case it will cause other problems, as you then loose the original pointer.
So the solution is to either use std::string passed by reference, or by using strcpy top copy into the destination memory area (but if you use strcpy you have to take care to not write beyond the allocated memory).
Try this inside modify strcpy(v, "123")
There are several problems with your code.
Your modify() function actually changes nothing:
int modify(char * v) {
v = "123"; // overwrites the parameter value copy on the stack
// with a char[] literal pointer
return 0;
}
You need to copy from the literal to the pointer:
int modify(char* v) {
strcpy(v,"123");
return 0;
}
You do not free the allocated memory, which may lead to memory leaks in other situations
int main (int argc, char** argv){
char *test = new char[10];
modify(test);
std::cout << test;
delete [] char; // <<< Note
return 0;
}
As Joachim Pileborg already mentioned the most approriate solution for c++ would be to use a std::string instead of char*.
Related
I am trying to print the following using the code as:
int main() {
char p[] = "hello";
char*t = p;
char**b = &t;
std::string s = b[0];
cout<<"string="<<s<<" b[0]="<<b[0];
}
The output I get is as expected:
string=hello b[0]=hello
Now the same thing I want to achieve using a function call in which I pass a variable by reference as:
void func(char**& p) {
char *k = (char*)malloc(8*sizeof(char));
k = (char*)"abc";
p = &k;
}
int main() {
char**j = NULL;
func(j);
std::string s1 = j[0];
cout<<s1;
}
Now I am getting a null string. What could be the reason and how to solve it ?
You have (at least) two problems:
The first is that you make p point to the local variable k.
The second is more subtle, and is that you reassign k losing the original memory you allocated and make k point to.
Then the usual spiel about never using arrays of char or pointers to char for strings, when you have std::string. And that you should never use malloc in C++, only new or new[]. And if you need new[] consider using std::vector instead (except for strings of course).
There is NO WAY to write code like this that follows any sort of standards of good programming. If you are serious about learning how to program you should abandon this mess and rewrite your code to do things the correct way. This is sort of mess is never necessary, even when interfacing with legacy code.
However the following 'works'
void func(char**& p) {
p = new char*;
*p = new char[8];
strcpy(*p, "abc");
}
And take note, I didn't need to use a cast.
This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 8 years ago.
Suppose I have the following functions:
char* allocateMemory()
{
char str[20] = "Hello world.";
return str;
}
int* another()
{
int x = 5;
return &x;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pString = allocateMemory();
printf("%s\n", pString);
int* blah = another();
printf("%d %d \n", blah, *blah);
return 0;
}
The first printf prints random values, because str IS LOCAL SCOPE.
The second printf prints the proper values, with blah = address of blah, *blah = 5
Why is it that local scope only affects allocateMemory which deals with arrays, but not integer?
Why does the first printf (returning char* ) prints random values and is affected by local scope, but not the second one (returning int* )?
Both ways of accessing the local variables of a method which goes out of scope is Undefined Behavior. These are some valid ways:
char* allocateMemory()
{
char* str= malloc(sizeof(char) * 20); //assuming C
strcpy(str, "Hello World.");
return str; //Valid
}
const char* allocateMemory()
{
return "Hello world."; //Valid Hello World is in read only location
}
int* another()
{
int *x = malloc(sizeof(int)); //assuming C
*x = 5;
return x; //Valid
}
char str[20] = "Hello world.";
str is local to function allocateMemory() and is no more valid once you exit the function and hence accessing it out of its scope if undefined behavior.
int x = 5;
The same applies here also.
You can have your data on heap and return the pointer to it is valid.
char *allocatememory()
{
char *p = malloc(20); /* Now the memory allocated is on heap and it is accessible even after the exit of this function */
return p;
}
Change the first function to:
char* allocateMemory()
{
static char str[20] = "Hello world.";
return str;
}
and see the difference.
And now explanation:
When you return address of local data (variable or array, does not matter - it is AUTOMATIC variables) you have a risk to lose data or make a mess in the memory. It was just a good luck that integer data was correct after the second function call. But if you return address of STATIC variables - no mistakes. Also you can allocate memory from HEAP for data and return address.
These are both, of course, UB, as the other answerers said. They also gave some good ways to do what you want to do in a proper fashion. But you were asking why does this actually happen in your case. To understand it, you need to understand what happens in the stack when you call a function. I'll try to provide a really simplified explanation.
When a function is called, a new stack frame is created on top of the stack. All the data in the function is put onto the stack frame. So, for the function
char* allocateMemory()
{
char str[20] = "Hello world.";
return str;
}
The stack frame for allocateMemory will contain, besides some other stuff, the 20 elements of the string (char array) str.
For this function:
int* another()
{
int x = 5;
return &x;
}
The stack frame for another will contain the contents of the variable x.
When a function returns, the stack pointer, which marks the top of the stack, drops all the way down to where it was before a function invocation. However, the memory is still there on the stack, it doesn't get erased - it is a costy and pointless process. However, there is no longer anything protecting this memory from being overwritten by something: it has been marked "unneeded".
Now, what's the difference between your calls to printf? Well, when you call printf, it gets its own stack frame. It overwrites what was left of the previous called function's stack frame.
In the first case, you just pass pString to printf. Then printf overwrites the memory that once was the stack frame of allocateMemory, and the memory that was once str gets covered with stuff printf needs to work with string output, like iteration variables. Then it proceeds to try and get memory pointed to by the pointer you passed to it, pString... But it has just overwritten this memory, so it outputs what looks like garbage to you.
In the second case, you first got the value of the pointer blah, which resides in your local scope. Then you dereferenced it with *blah. Now comes the fun part: you've done the dereferencing before you've called another function which could overwrite the contents of the old stack frame. Which means the memory that was once the variable x in the function another is sort of still there, and by dereferencing the pointer blah, you get the value of x. And then you pass it to printf, but now, it doesn't matter that printf will overwrite another's stack frame: the values you passed to it are now sort of "safe". That's why the second call to printf outputs the values you expect.
I've heard of people who dislike using the heap so much that they use this "trick" in the following way: they form a stack array in a function and return a pointer to it, then, after the function returns, they copy its contents to an array in the caller's scope before calling any other function, and then proceed to use it. Never do this, for the sake of all the people who may read your code.
I am trying to understand char pointer in C more but one thing gets me.
Supposed I would like to pass a char pointer into a function and change the value that pointer represents. A example as followed:
int Foo (char *(&Msg1), char* Msg2, char* Msg3){
char *MsgT = (char*)malloc(sizeof(char)*60);
strcpy(MsgT,"Foo - TEST");
Msg1 = MsgT; // Copy address to pointer
strcpy(Msg2,MsgT); // Copy string to char array
strcpy(Msg3,MsgT); // Copy string to char pointer
return 0;
}
int main() {
char* Msg1; // Initial char pointer
char Msg2[10]; // Initial char array
char* Msg3 = (char*)malloc(sizeof(char) * 10); // Preallocate pointer memory
Foo(Msg1, Msg2, Msg3);
printf("Msg1: %s\n",Msg1); // Method 1
printf("Msg2: %s\n",Msg2); // Method 2
printf("Msg3: %s\n",Msg3); // Method 3
free(Msg1);
free(Msg3);
return 0;
}
In the above example, I listed all working methods I know for passing char pointer to function. The one I don't understand is Method 1.
What is the meaning of char *(&Msg1) for the first argument that is passed to the function Foo?
Also, it seems like method 2 and method3 are widely introduced by books and tutorials, and some of them even referring those methods as the most correct ways to pass arrays/pointers. I wonder that Method 1 looks very nice to me, especially when I write my API, users can easily pass a null pointer into function without preallocate memory. The only downside may be potential memory leak if users forget to free the memory block (same as method 3). Is there any reason we should prefer using Method 2 or 3 instead Method 3?
int f(char* p) is the usual way in C to pass the pointer p to the function f when p already points to the memory location that you need (usually because there is a character array already allocated there as in your Method 2 or Method 3).
int f(char** p) is the usual way in C to pass the pointer p to the function f when you want f to be able to modify the pointer p for the caller of this function. Your Method 1 is an example of this; you want f to allocate new memory and use p to tell the caller where that memory is.
int f(char*& p) is C++, not C. Since this compiles for you, we know you are using a C++ compiler.
Consider what happens when you take an argument of type int& (reference to int) :
void f(int &x) {
x++;
}
void g(int x) {
x++;
}
int main() {
int i = 5;
f(i);
assert(i == 6);
g(i);
assert(i == 6);
}
The same behaviour can be achieved by taking a pointer-to-int (int *x), and modifying it through (*x)++. The only difference in doing this is that the caller has to call f(&i), and that the caller can pass an invalid pointer to f. Thus, references are generally safer and should be preferred whenever possible.
Taking an argument of type char* (pointer-to-char) means that both the caller and the function see the same block of memory "through" that pointer. If the function modifies the memory pointed to by the char*, it will persist to the caller:
void f(char* p) {
(*p) = 'p';
p = NULL; //no efect outside the function
}
int main() {
char *s = new char[4];
strcpy(s, "die");
char *address = s; //the address which s points to
f(s);
assert(strcmp(s, "pie") == 0);
assert(s == address); //the 'value' of the variable s, meaning the actual addres that is pointed to by it, has not changed
}
Taking an argument of type char*& ( reference-to-(pointer-to-char) ) is much the same as taking int&:
If the function modifies the memory pointed to by the pointer, the caller will see it as usual. However, if the function modifies the value of the pointer (its address), the caller will also see it.
void f(char* &p) {
(*p) = 'p';
p = NULL;
}
int main() {
char *s = new char[4];
strcpy(s, "die");
char *address = s; //the address which s points to
f(s);
assert(strcmp(address, "pie") == 0); //the block that s initially pointed to was modified
assert(s == NULL); //the 'value' of the variable s, meaning the actual addres that is pointed to by it, was changed to NULL by the function
}
Again, you could take a char** (pointer-to-pointer-to-char), and modify f to use **p = 'p'; *p = NULL, and the caller would have to call f(&s), with the same implications.
Note that you cannot pass arrays by reference, i.e. if s was defined as char s[4], the call f(s) in the second example would generate a compiler error.
Also note that this only works in C++, because C has no references, only pointers.
You would usually take char** or char*& when your function needs to return a pointer to a memory block it allocated. You see char** more often, because this practice is less common in C++ than in C, where references do not exist.
As for whether to use references or pointers, it is a highly-debated topic, as you will notice if you search google for "c++ pointer vs reference arguments".
I'm looking for a way to associate a char array with a string so that whenever the char array changes, the string also changes. I tried to put both char array and string variables in a union but that didn't worked as the compiler complained...
Any ideas are welcome...
class Observable_CharArray
{
char* arr;
std::function<void(char*)> change_callback;
public:
Observable_CharArray(int size, std::function<void(char*)> callback)
: arr(new char[size]), change_callback(callback){}
~Observable_CharArray()/*as mentioned by Hulk*/
{
delete[] arr;
}
void SetCallback(std::function<void(char*)> callback)
{
change_callback = callback;
}
/*other member function to give access to array*/
void change_function()
{
//change the array here
change_callback(arr);
}
};
class Observer_String
{
std::string rep;
void callback(char* cc)
{
rep = std::string(cc);
}
public:
Observer_String(Observable_CharArray* och)
{
och->SetCallback(std::bind(&callback, this, _1));
}
/*other member functions to access rep*/
};
The design can definitely be improved.
There can be other ways to solve your actual problem rather than observing char arrays.
The problem is that the std::string may change the string array inside (especially when it resizes). For instance, c_str returns the address of the current string - documentation says that "The pointer returned may be invalidated by further calls to other member functions that modify the object.".
If you're sure you won't call string methods (hence the string will stay at the same memory location), you could try accessing the c_str pointer (your char array) directly and modify its content.
std::string str = "test";
char* arr = (char*)str.c_str();
arr[3] = 'a';
NOTE: I strongly advice against this unless in a testing context.
In other words, the string class doesn't guarantee it's going to stay in the same place in memory - meaning trying to access it through a char array is impossible.
The best is to create another string class that enforces the char array to always stay the same size (and so can stay in the same memory position all the time). You could also create a bigger array (max size string for instance) to cope with any string size changes - but that should be enforced in your wrapper class.
Well you can do this, but you shouldn't
#include <iostream>
#include <string>
int main()
{
std::string test("123456789");
std::cout << test << "\n";
char* data = &test.front(); // use &(*test.begin()) for pre-C++11 code
for ( size_t i(0); i < test.size(); ++i )
{
data[i] = 57 - i;
}
std::cout << test << "\n";
}
Output will be
123456789
987654321
This however goes again everything std::string is trying to facilitate for you. If you use data, you risk causing UB and changes to test may make data point to garbage.
You should not do this!
However, there are many (dangerous) ways to achieve it:
char* cStr = const_cast<char*>(cppStr.c_str());
or
char* cStr = const_cast<char*>(cppStr.data());
or
char* cStr = &cppStr[0];
But beware that the cppStr might be reallocated whenever you touch it, hence invalidating your cStr. That would crash at some point in time, although maybe not immediately (which is even worse).
Therefore, if you are going to do this anyway. Make sure to cppStr.reserve(SOMETHING) *before* you get the cStr out of it. This way, you will at least stabilise the pointer for a while.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ deprecated conversion from string constant to 'char*'
I want to pass a string via char* to a function.
char *Type = new char[10];
Type = "Access"; // ERROR
However I get this error:
error: deprecated conversion from string constant to 'char*'
How can I fix that?
If you really want to modify Type:
char *Type = new char[10];
strcpy( Type, "Access" );
If you don't want to modify access:
const char *Type = "Access";
Please note, that, however, arrays of char in C and in C++ come with a lot of problems. For example, you don't really know if the call to new has been successful, or whether it is going to throw an exception. Also, strcpy() could surpass the limit of 10 chars.
So you can consider, if you want to modify type later:
std::string Type = "Access";
And if you don't want to modify it:
const std::string Type = "Access";
... the benefit of using std::string is that it is able to cope with all these issues.
There are a couple of things going on here.
char *Type = new char[10];
This create a char* pointer named Type and initializes it to point to the first element of a newly allocated 10-element array.
Type = "Access"; // ERROR
This assignment doesn't do what you think it does. It doesn't copy the 6-character string "Access" (7 characters including the terminating '\0') to the array you just created. Instead, it assigns a pointer to the first element of that array into your pointer Type. There are two problems with that.
First, it clobbers the previous value of Type. That 10-character array you just allocated now has nothing pointing to it; you can no longer access it or even deallocate it. This is a memory leak.
This isn't what the compiler is complaining about.
Second, a string literal creates a statically allocated const array ("statically allocated" meaning it exists for the entire execution of your program). Type is not declared with a const qualifier. If the compiler allowed you to point Type to the string "Access", you could use that pointer to (attempt to) modify it:
Type = "Access";
Type[0] = 'a'; // try to change the string to "access"
The purpose of const is to prevent you from modifying, or even attempting to modify, things that are read-only. That's why you're not allowed to assign a non-const pointer value to a const pointer object.
Since you're programming in C++, you're probably better off using std::string.
I want to pass a string via char* to a function.
Here is how you can pass a string via char* to a function (note the required const keyword in the function signature.)
#include <iostream>
void f(const char* p) {
std::cout << p << "\n";
}
int main() {
f("Access");
}
But, what if you are invoking an existing function, and cannot modify its signature?
If you have some external guarantee that the function will not write through its argument pointer,
#include <iostream>
void f(char* p) {
std::cout << p << "\n";
}
int main() {
f(const_cast<char*>("Access"));
}
If, on the other hand, the function might write to the string, then you'll need to allocate space for the string:
#include <iostream>
void f(char* p) {
*++p;
std::cout << p << "\n";
}
int main() {
// Allocate read-write space on the heap
char *p = new char[strlen("Access"+1)];
// Copy string to allocated space
strcpy(p, "Access");
f(p);
delete p;
}
or,
#include <iostream>
void f(char* p) {
*++p;
std::cout << p << "\n";
}
int main() {
// Allocate read-write space on the stack
char arr[] = "Access";
f(arr);
}
But, the best course by far is to avoid the whole pointer mishegas:
#include <iostream>
void f(const std::string& p) {
std::cout << p << "\n";
}
int main() {
f("Access");
}
You've got a basic operations problem here, not a coding issue.
When you want to change the contents of a C char array, you do not use the assignment operator. That will instead change the value of the underlying pointer. Ick.
Instead you are supposed to use the C string library routines. For instance, strcpy (Type, "Access"); will copy the string literal "Access" into your character array, with its all-important trailing nul character.
If you are using C++ (as your tags indicate), you should probably be using std::string instead of arrays of char. Assignment works they way you are expecting there.