segmentation fault for the code - c++

#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).

Related

pointer aritmetic changes depending on output? [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 6 years ago.
I have these two almost identical bits of c++
#include <iostream>
using namespace std;
int main(){
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int *p = &a;
cout << &c << endl;
cout << *(p+1);
}
with the output:
0x7ffd7b16998c
2
and
#include <iostream>
using namespace std;
int main(){
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int *p = &a;
cout << &d << endl;
cout << *(p+1);
}
which produces the output:
0x7ffdb7ea105c
3
Why does the value of *(p+1) depend on what I output beforehand?
If I delete the line
cout << &c << endl;
completely i get the expected 1 as an output.
What on earth is happening?
What's happening is undefined behavior.
When you obtain a pointer to an int, you are allowed to use the value of that pointer alone; pointer arithmetic is meaningless.
In order for p+1 to produce an address that you can dereference, p must point to an array element other than its last element. In all other situations, reading *(p+1) is undefined.
Standards aside, the CPU must be taking that value from some place. You assume that the place must be the address of b, which is declared immediately after a. However, C++ makes no guarantees about location of local variables in memory relative to each other. It appears that the compiler reorders your variables, producing an output that you did not expect (and it's undefined anyway).
*(p+1) accesses memory after a so it's Undefined Behaviour.
Propably you intended (*p)+1 to increase a by 1?

Getline() keeps skipping lines in for loop

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.

What is (int*)?

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.

Segmentation fault while using delete in c++

I am getting seg fault while trying to delete a pointer(for char array). Please help me. Am i doing anything wrong here. Please find the code snippet and output below.
Code :
# include <iostream>
using namespace std;
int main()
{
int *p = new int;
const char* c = new char[100];
c = " hello";
*p = 10;
cout << "c= " << c << "*p = " << *p << endl;
delete p;
delete c;
c = NULL;
p = NULL;
return 0;
}
output:
c= hello*p = 10
Segmentation fault (core dumped)
Edit :
If i do not use new and delete for a character array, Is it a memory leak? I can not use string in my code, so what is the correct way to use const char* variable?
Thanks in advance.
You allocate memory and assign it to the pointer c here
const char* c = new char[100];
But then you reassign the pointer:
c = " hello";
That means you loose the original pointer, and now c points to the literal string "hello" which you can't delete.
What you should to instead is copy the string into the allocated memory.
You are making c point to a string literal here:
c = " hello";
then you attempt to delete it
delete c;
This is undefined behaviour. And you leak the array c pointer to originally.
Note: if c pointed to the original dynamically allocated array, you would need to delete it by calling delete [], not delete. Also, in C++ you would usually avoid such manual memory allocation:
#include <string>
#include <iostream>
int main()
{
std::string c = "hello";
int p = 10;
std::cout << "c= " << c << ", p = " << p << std::endl;
}
c = " hello";
Makes it point to a static const char buffer(string literal) that you don't have control on. It does not copy the string in the array. When calling delete on this kind of memory, you get the crash.
You will also never be able to free the originally allocated memory.
If you want to do so:
delete [] c;
is what you need.
your code is trying to delete a variable in read only data section, hence getting a segmentation fault.
And the code also contains a memory leak, c = new char[100] causes to allocated 100 bytes, and then the c pointer points to the "hello" literal, hence the address that was received using new is lost, hence a memory leak..
use string copy function to copy the literal "hello" to the allocated memory.

Why does my code produce a segmentation fault?

#include <iostream>
using namespace std;
int main ()
{
int **a;
int b[5] = {3,4,5,6,1};
*a=b;
cout << *((*a)+0) << endl;
return 0;
}
According to my understanding *((*a)+0) is equivalent to (*a)[0]. Am I wrong? How can I make the above code print the first element of the array?
And why does this code work?
#include <iostream>
using namespace std;
int main ()
{
int *a;
int b[5] = {3,4,5,6,1};
a=b;
cout << *(a+0) << endl;
return 0;
}
When I replace a with *a everywhere, why is it wrong?
You access an uninitialized pointer in
*a=b;
At this point a points to a random location, and as is the rule with undefined behavior you can't predict what will happen. For you it seems to be a location that you can't write to, and so you get a crash.
The second variant works because then you make a point to b, you don't write to an uninitialized pointer, you actually initialize the pointer with the location of the first item in b.