#include <iostream>
using namespace std;
int main()
{
char * a = nullptr;
{
char * b = (char *) "hello";
a = b;
}
cout << a << endl; // prints hello
return 0;
}
I have the code above. I am having hard time understanding why the code doesnt crash. My reasoning is I expected a crash because I am passing pointer b to upper scope with pointer a and using it to cout. Since "hello" was created within b's scope and new keywords isnt used, I expected it to clean itself automatically like a variable in a scope. What am I thinking wrong??
C-style string literal like "hello" has static storage duration; it exists in the life of the program. Then it's still valid for cout << a << endl; (while a is pointing to it) after the scope where b is defined.
String literals have static storage duration, and thus exist in memory for the life of the program.
Related
I'm trying to print the value of variables, one of them is pointer and the second one is simply an int.
I did assign a value to a pointer - a, and than I assigned pointer to variable. I'm trying to output the value of variable which meant to show the value of pointer, but I got nowhere.
Since the compiler shows the following warning:
'a' is used unitialized in this function
and eventually after compilation proccess is done I get the error while running program, windows pop-up tells me that:
"The instruction at 0x00401359 referenced memory at 0x00417c7e. The memory could not be written. Click on OK to terminate the program."
What is wrong with this piece of code ?
#include <iostream>
using namespace std;
int main(void)
{
int *a;
int b;
*a = 5;
b = *a;
cout << b << " " << *a;
}
a is a pointer and it should point somewhere. If you do not initialize it, it points just anywhere, thus your assignment *a=5 tries to write into a random memory address.
#include <iostream>
using namespace std;
int main(void)
{
int c; // reserves some space for a to point to
int *a = &c; // NOW a is initialized and it points to c
int b;
*a = 5; // writes 5 into the variable c
b = *a;
cout << b << " " << *a;
}
#include <iostream>
using namespace std;
int main(void)
{
int *a;
int b;
a=&b;
*a = 5;
cout << b << " " << *a;
}
Your pointer a does not have a variable address on which it can save this value.
I was trying to access the private data members of the class. Everything was going fine until I came upon the int*. I don’t get what it is. I think it’s something that we can use to create a new memory address.
My code :
#include <iostream>
using namespace std;
class x
{
int a, b, c, d;
public:
x()
{
a = 100;
b = 200;
c = 300;
d = 400;
}
};
int main()
{
x ob;
int *y = (int *)&ob;
cout << *y << " " << y[1] << " " << y[2] << " " << y[3] << endl;
}
Can anyone help me in understanding it?
Its a c-style cast to access the memory occupied by the struct x as a set of ints.
It takes the address of ob, casts it from 'address of' (ie a pointer to) x into a pointer to int. The compiler happily assigns this cast to y, so you can manipulate it, or in this case, print out the memory blocks as ints. As the struct happens to be a group of ints anyway, it all works even though its a bit of a hack. I guess the original coder wanted to print out all 4 ints without having to specify each one in turn by variable name. Lazy.
Try using a cast to a char* (ie 1 byte at a time) and print those out. You'll be basically printing out the raw memory occupied by the struct.
A good C++ way would be to create an operator<< function that returns each variable formatted for output like this, then write cout << ob << endl; instead.
I have the following sample code. Just wanted to know if is valid to take address of a local variable in a global pointer and then modify it's contents in a sub function. Following program correctly modifies value of variable a . Can such practice cause any issues ?
#include <iostream>
#include <vector>
using namespace std;
vector<int*> va;
void func()
{
int b ;
b = 10;
int * c = va[0];
cout << "VALUE OF C=" << *c << endl;
*c = 20;
cout << "VALUE OF C=" << *c << endl;
}
int main()
{
int a;
a = 1;
va.push_back(&a);
func();
cout << "VALUE IS= " << a << endl;
return 0;
}
This is OK, as long as you don't try to dereference va[0] after a has gone out of scope. You don't, so technically this code is fine.
That said, this whole approach may not be such a good idea because it makes code very hard to maintain.
I'd say that if your program grows you could forget about a change you made in some function and get some weird errors you didn't expect.
Your code is perfectly valid as long as you call func() while being in the scope of a. However, this is not considered to be a good practice. Consider
struct HugeStruct {
int a;
};
std::vector<HugeStruct*> va;
void print_va()
{
for (size_t i = 0; i < va.size(); i++)
std::cout<<va[i].a<<' ';
std::cout<<std:endl;
}
int main()
{
for (int i = 0; i < 4; i++) {
HugeStruct hs = {i};
va.push_back(&hs);
}
print_va(); // oups ...
}
There are 2 problems in the code above.
Don't use global variables unless absolutely necessary. Global variables violate encapsulation and may cause overlay of variable names. In most cases it's much easier to pass them to functions when needed.
The vector of pointers in this code looks awful. As you can see, I forgot that pointers became invalid as soon as I left for-loop, and print_va just printed out garbage. The simple solution could be to store objects in a vector instead of pointers. But what if I don't want HugeStruct objects to be copied again and again? It can take quite a lot of time. (Suppose that instead of one int we have a vector of million integers.) One of the solutions is to allocate HugeStructs dynamically and use vector of smart pointers: std::vector<std::shared_ptr<HugeStruct>>. This way you don't have to bother about memory management and scope. Objects will be destroyed as soon as nobody will refer to them.
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
using namespace std;
union type{
int a;
char b;
int *p;
char *s;
int arr[10];
};
int fn(union type *exp){
exp->p = exp->p+1;
cout << *(exp->p);
cout << "\n";
return 0;
}
int main(){
union type *str;
str->a = 10;
str->b = 'n';
str->p = &(str->a);
cout << (str->p);
cout << "\n";
fn(str);
cout << str->p;
cout << "\n";
return 0;
}
This code is giving me segmentation fault. Is it because i need to allocate memory to the union explicitly using malloc?? I am new to coding and trying to learn c++.
This code is giving me segmentation fault. Is it because i need to
allocate memory to the union explicitly using malloc??
Right. Your str pointer isn't pointing to valid memory location, it even not initialized. So, before writing str->a you need to set str to something.
You are declaring a pointer to a union, but the pointer is not pointing to any valid memory, which you need to either malloc/new. What it is pointing to is undefined (garbage pointer).
Say I have this simple program
#include <iostream>
using namespace std;
struct teststruct
{
int n;
long l;
string str;
};
int main()
{
teststruct wc;
wc.n = 1;
wc.l = 1.0;
wc.str = "hello world";
//cout << wc << endl; // what is wc by itself?
cout << &wc; // contains the memory address to the struct?
return 0;
}
I'm trying to understand what is in wc? When I declare a struct type with the variable name wc; what is wc? Is it a pointer to a memory address? I've tried to cout the contents, but the code gives me an error. Can you please clarify what is wc
what is wc? Is it a pointer to a memory address?
No, it's a lump of storage large enough to contain all of the members of teststruct.
In this case, it has automatic storage, which means that it lasts as long as the code block that contains it - in this case, until the end of main(). The details of where it's stored are implementation specific, but in practise it will usually be stored in a temporary area of the thread's stack (a stack frame), created when the function begins and destroyed when the function exits.
The exact details of how the members are located within that storage are also implementation-specific.
I've tried to cout the contents, but the code gives me an error.
That only works for types that have the << operator overloaded. The standard library does that for all fundamental types and pointers, and for some library types like std::string; but if you want support for your own types, then you'll need to supply your own overload, for example:
std::ostream & operator<<(std::ostream & s, teststruct const & t) {
return s << t.n << ',' << t.l << ',' << t.str;
}
cout << wc << endl; // prints "1,1,hello world"
wc is instance of type teststruct with automatic storage. Every other detail is implementation specific, yet, in most cases, implementations use stack as automatic storage area.
&wc is expression of type teststruct *, resulting in wc's address.
As for the unasked question (why don't you just ask it?): to output contents of the struct, you have to output its members one by one:
cout << wc.n << ", " << wc.l << ", " << wc.str << endl;
Yet, there seems to be misconception in your code; 1.0 is literal of type float, that is, it's floating point number. Are you sure it's what you want to store in long variable? If you want long literal, use 1L.
wc is an object of type teststruct allocated on the stack
Think of an instance of teststruct as a contiguous region of memory that is used to contain the value of its member variables. When you are printing
cout << &wc;
you are outputting the address of your variable, that is the location in memory at which it is stored. This is a simplistic answer and likely full of detailed technical error, but the nature and wording of your question suggest that it might paint a useful picture to you.