Does char* have other functions than as a pointer in C++? [duplicate] - c++

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 3 years ago.
If char* is a pointer (I find its size is always 4 bytes), how do I find its value (the address in hexa or decimal)? I tried &(*p) for char *p. It simply returned the initial string. If it is always 4 bytes, how is it that it can be initialized to long strings but point to the first character? In other words where is the string stored?
Is char* a weird pointer used for purposes other than what a pointer is intended to be?

// an initial pointer (usually its size is 32bit or 64bit, depending on CPU/OS).
// it's value is currently NULL (not pointing anywhere),
// so we can't do very much with this right now.
char* p = nullptr;
// for the sake of sanity, check the value (should be zero)
// we have to convert to intptr_t, otherwise we'd get the string
// value being printed out.
std::cout << "p address = " << intptr_t(p) << std::endl << std::endl;
// lets allocate a few chars to play with
p = new char[10];
// copy in some text value
std::strcpy(p, "Hello");
// and now if we print the address, the text string,
// and the char we are pointing at
std::cout << "p address = " << intptr_t(p) << std::endl;
std::cout << "p string = " << p << std::endl;
std::cout << "p dereferenced = " << *p << std::endl << std::endl;
// for fun, lets increment the pointer by 1
++p;
// this should have made a couple of changes here
std::cout << "p address = " << intptr_t(p) << std::endl;
std::cout << "p string = " << p << std::endl;
std::cout << "p dereferenced = " << *p << std::endl << std::endl;
// decrement again (so we can delete the correct memory allocation!)
--p;
// now free the original allocation
delete [] p;
// if we print again, notice it still has the memory location?
std::cout << "p address = " << intptr_t(p) << std::endl;
// This would be bad to access (we've just deleted the memory)
// So as a precaution, set the pointer back to null
p = nullptr;
// should be back where we started
std::cout << "p address = " << intptr_t(p) << std::endl;

Related

Grabbing the address of the pointer variable itself, instead of the address that we are pointing to, in C/C++?

Let's consider I have the following x pointer variable in my function:
int* x = new int { 666 };
I know I can print its value by using the * operator:
std::cout << *x << std::endl;
And that I can even print the address of where the 666 is being stored on the heap, like this:
std::cout << (uint64_t)x << std::endl;
But what I'd like to know is on whether it's also possible to grab the address of the x variable itself, that is, the address of the region of memory in the stack containing the pointer to the heap int containing 666?
Thanks
Just use another &
std::cout << (uint64_t)&x << std::endl;
e.g.:
int v = 666; // variable
int * x = &v; // address of variable
int ** p = &x; // address of pointer x
and so on
int *** pp = &p;
int **** ppp = &pp;
and how to access to it:
std::cout << ****ppp << " == " << ***pp << " == "
<< **p << " == " << *x << " == " << v << std::endl;

c++ segfault and pointers confusion (I have the feeling I'm missing something terribly obvious)

I'm a python programmer new to C++. Currently getting a segfault when trying to play around with pointers. Can someone explain this behavior? I suspect there's something significant about cout that I'm not understanding.
#include<iostream>
using namespace std;
int main() {
int var; // declaration
cout << "var declared" << endl;
cout << "var : " << var << endl;
cout << "&var : " << &var << endl;
var = 10; // initialization
cout << "\nvar initialized" << endl;
cout << "var : " << var << endl;
cout << "&var : " << &var << endl;
int* ptr; // declaration
cout << "\nptr declared" << endl;
cout << "ptr : " << ptr << endl;
cout << "*ptr : " << *ptr << endl;
cout << "&ptr : " << &ptr << endl;
ptr = &var; // initialization
cout << "\nptr initialized : " << endl;
cout << "ptr : " << ptr << endl;
cout << "*ptr : " << *ptr << endl;
cout << "&ptr : " << &ptr << endl;
return 0;
}
using this compiler command
g++ --std=c++14 main.cpp -o main_exec;
This code produces the following output
var declared
var : 0
&var : 0x7fff55724478
var initialized
var : 10
&var : 0x7fff55724478
ptr declared
ptr : 0x0
[1] 82727 segmentation fault ./main_exec
This code obviously compiles but produces a segfault at runtime.
Things I've tried
I've tried combinations of commenting out the lines that include *ptr and the lines that include &ptr, short story is some combinations produce no segfault. It seems that I can use *ptr 1 time and not in combination with &ptr
You declared a pointer to an integer, but not initialized or assigned it with any pointer (i.e. to memory address of an integer variable).
int* ptr; // declaration
The line above says, ptr is a pointer (that would point to memory address of an integer variable). In your case it just says it is a pointer, what it does point is not defined.
When you hit this line,
cout << "*ptr : " << *ptr << endl;
Here *ptr means, get the value at address (the address that actually would store the value) and is being pointed by ptr. However ptr points to nothing. So you're trying to access memory in a way that is not permitted which leads to the segmentation fault.
Just remember that pointers are variable that as their values store memory address of another variable.
int *ptr; // would store memory address of an integer type variable.
int a = 5; // would store an integer variable.
ptr = &a; // Here &a gets the address of variable a and stores in *ptr
cout<<*ptr // Here *ptr gets the value of variable whose memory address is pointed to by *ptr.
Edit
To answer the question if int * ptr = new int; is valid.
Yes it will reserve you a memory location and allows you to later store values on that location later, as shown in code below,
int* ptr = new int; // gets memory address and assigns to *ptr
*ptr = 5; // assigns value 5 to the memory being pointed by *ptr
cout<<*ptr; // output 5
However you're supposed to not do this unless you've a particular need.
Variables reserve you memory, and give you a friendly variable name of your choice.
Anything you create with new is not deleted automatically, as suggested in comment section.
Variables, in contrast to this, are deleted automatically when they get out of scope (block, function, loop, etc.)

Changing the value of a pointer passed by reference [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I have this maybe weird question. I was considering following example where I pass a pointer by reference so if I change the pointer address of the argument the initial pointer should also change the address. And indeed this happens.
However the value of a in the main method will have some random value and not 3 as the q variable inside changePointer whose address we use to change pointer a to.
Is there something stupid oversee or is the whole thing just undefined behaviour.
#include <iostream>
void changePointer(int* &p) {
int q = 3;
std::cout << "Address of q: " << &q << std::endl;
p = &q;
std::cout << "Value of p: " << *p << std::endl;
}
int main() {
int* a = new int(4);
changePointer(a);
std::cout << "Adress of a: " << a << std::endl;
std::cout << "Value of a: " << *a << std::endl;
}
This is undefined behavior because you access a local variable which is already vanished.
Try adding static before int q = 3; and making the variable static so that the variable won't vanish on returning from the function.
Also, please do not cause memory leak by allocating some buffer to a and throwing it away!
q is scoped variable, it gets destroyed when changePointer returns. a then points to freed memory, so it's invalid pointer, and dereferencing it (*a) is Undefined Behavior.
Corrected code:
void changePointer(int* &p) {
int* q = new int(3); // this way q lives until you delete it
std::cout << "Address of q: " << q << std::endl;
delete p; // we don't want unfreeable memory
p = q;
std::cout << "Value of p: " << *p << std::endl;
}
int main() {
int* a = new int(4);
changePointer(a);
std::cout << "Adress of a: " << a << std::endl;
std::cout << "Value of a: " << *a << std::endl;
delete a;
}
q is a local variable inside changePointer, so when changePointer exits the address of q contains garbage.

C++ string pointer doesn't have the same memory address as the string it points to

I wrote a simple program to see how C++ handles pointers to string objects (new to OOP), and I was suprised to see that string* as which was assigned the memory address of string a, didn't store a value equivalent to &a. Also, the console didn't print the value to *as. Could this be an error on my end or the system, or am missing something fundamental here?
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
string a = "asdf";
string* as = &a;
string* as_holder = &a;
int main()
{
cout << "a = " << a << "\t" << "&a = " << &a << " *as = " << *as << endl
<< "as = " << as << endl
<< "++as = " << ++as << endl
<< "*as = " << *as << endl << endl;
return 0;
}
output:
a = asdf &a = 011ff68C *as =
as = 011FF6A8
++as = 011FF6A8
*as =
In my test of the valid portion of your program (the first two lines of cout), the printout showed the same address:
a = asdf &a = 0x8049c90 *as = asdf
as = 0x8049c90
(link to a demo)
Lines three and four, however, amount to undefined behavior: once you do ++as, you are moving the pointer to the next std::string in an "array of strings" (which does not exist). Therefore, the subsequent attempt at dereferencing as is undefined behavior.
If you would like to obtain a pointer to the data of your string, such that you could move to the next character by incrementing the pointer, you could use c_str() member function, like this:
const char *as = a.c_str();
as++;
cout << as << endl; // This would print "sdf"

pointer to array c++

My understanding about assigning an array to a pointer is that the pointer is pointing at the first index of the array, so when printout the pointer, it should print out the address of the first index of the array, but how come in this case the cout printed out the value of the whole array? even though I explicitly indicated that I wanted the address of the first index
char foo[] = {'A','B','C','\0'};
char* p = foo;
char* q = &(foo[0]);
cout <<"from p: " << p << endl;
cout << "from q: " << q << " " << &(foo[0]) << endl;
//output
from p: ABC
from q: ABC ABC
the second question is that I see the difference between those two lines is that one is an array of pointer to char, the other is a pointer to a char array, is that correct? is the parenthesis necessary?
char* bar1[4];
char (*bar2)[4] = &foo;
cout << "address of foo is " << bar2 << endl;
//output
address of foo is 0x7fff192f88b0
The address of the foo array should be the same as the address of A, right? How do I printout the address of A? since I failed to do so. Thank you very much
<< has a dedicated overload for const char *, because that's what a C-style string is. Try this:
cout << static_cast<const void *>(bar2) << endl;