Segmentation 11 in Linux issue - c++

I am doing a buffer overflow problem and I trying to print hello world. Below is my code to
but I am getting a segmentation 11 issue when I run this file with another one. "./executable < input.cpp(This is the file below). I am doing something wrong to solve a buffer overflow issue?
#include<stdio.h>
using namespace std;
main()
{
printf("A");
//00000b00
for (int i = 0; i < 4; i++)
printf("%c%c%c%c",0x00,0x0b,0x00,0x00);
}
Below is the actual code that I am trying to print hello world. Above is my input string.
#include <iostream>
using namespace std;
int i;
unsigned int* p;
void f1() {
int a=10;
char str[4];
cout << "Please enter a string:";
while (!cin.eof()) {
cin.get(str[i]);
i++;
}
printf("address of str is:%x\n",str);
cout << "The string you entered is:";
printf("address of a is:%x\n",&a);
cout << str << endl;
}
void f2()
{
cout << "Hello World!\n";
}
main()
{
printf("The address of function f2:%08x\n",f2);
f1();
}

I am getting a segmentation 11 issue when I run this file with another one.
./executable < input.cpp
I am doing something wrong to solve a buffer overflow issue?
Yes. Buffer overflow attacks don't work like that - dumping a bunch of C source code into memory does not magically make the machine compile and run it. To generalize wildly, the data you dump into memory must contain:
Padding to force the following data to lie in the right place in the stack
A replacement address in the location of the old return address, pointing to the following executable code
Some more padding, usually a "NOP slide"
Some executable code
Please read the classic "Smashing the stack for fun and profit", and keep in mind that you may have to disable some protections (non-executable stack, ASLR, stack canary) to get these exploits to work on a modern system.

Use the %x modifier to print hexadecimal values
If this is a C program, then the use of namespace std makes no sense
#include<stdio.h>
int main(void)
{
puts("A");
for (int i = 0x0; i < 4; i++)
printf("%x\n", i);
return 0;
}
Op's post was updated:
#include<stdio.h>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int i = 0; //Initialise i
void f1() {
int a=10;
char str[4];
cout << "Please enter a string: ";
while (!cin.eof() && i < 4 ) { //Have a condition on length of string
cin.get(str[i]);
i++;
}
str[i] = '\0'; //Set the eof character at end of the string
printf("address of str is: %p\n", str);
printf("address of a is: %p\n", &a);
cout << "The string you entered is: " << str << endl;
}
void f2() {
cout << "Hello World!\n";
}
int main()
{
printf("The address of function f2: %p\n", f2); //To print address use the %p option
f1();
return 0;
}

Related

why pointer to a string is is giving me blank output

i am running this in vs code.
its just taking input and then it terminates.
the output is blank.
this is the output
///
PS D:\c++\string> cd "d:\c++\string" ; if ($?) { g++ chararray.cpp -o chararray } ; if ($?) { .\chararray }
uu uugg gg
///
heres the code.
#include <iostream>
using namespace std;
int main()
{
char *u;
cin.getline(u, 19);
cout << "well " << u;
}
The local buffer char *u; hasn't been initialized, it may cause a SEGV crash, since calling getline will lead to writing into the address stored in u, and it's a random value now.
It would be better to use the alternative std::getline and std::string as the target string type, then we read an arbitrary length of the string (We void buffer overflow and other kinds of memory issues):
#include <iostream>
int main() {
std::string line;
std::getline(std::cin, line);
std::cout << "well " << line;
return 0;
}
A better way would be to do some allocation of mem before you store some data there.
#include <iostream>
using namespace std;
int main()
{
char *u = new char[20];
// char u[20] = { "\0" }; // with this you do not need to delete the mem
cin.getline(u, 19);
cout << "well " << u;
delete [] u; // do not forget to free your heap memory
}

c++ ifstream , Reading from file crashes

At the beginning I apologize for my English.
I was trying to write a XML Parser that I encountered a weird problem.
to explain my problem I should say, I have a xml parser class that has an ifstream member. And this class has a function which reads until it reaches an open tag matching with the given input.
this is the parser class I was working on:
// XMLParser.cpp
#include <fstream>
#include "Stack.h"
using namespace std;
class XMLParser{
private:
int charReadRate = 3;
public:
ifstream *stream;
XMLParser(string add){
stream = new ifstream(add); // open input stream
}
void nextTag(string tag){
// find the first occurance of open-tag with name 'tag'
cout << "nextTag\n";
char * readData;
string tagName="";
stream->read(readData, charReadRate);
int len = string(readData).length();
int i = 0;
// cout << len << endl;
while(true){
if((*readData) == '<'){
readData++;
i++;
while(*readData != '>'){
tagName+=*readData;
readData++;
i++;
if(i>=len){
if(stream->eof()){
return ; // error didn't find
}
stream->read(readData, charReadRate);
// cout << readData << endl;
len = string(readData).length();
i = 0;
}else{
if(tagName == tag){
// cout << "find\n";
stream->seekg(i-len, ios::cur);
return;
}
}
}
}else{
readData++;
i++;
if(i>=len){
if(stream->eof()){
return ; // error didn't find
}
stream->read(readData, charReadRate);
len = string(readData).length();
i = 0;
}
}
}
}
};
in the nextTag function I read the file until I reach the open tag which name's matches with the given input.
and here is my main function
int main(){
XMLParser parser("test.xml");
cout << "ready\n";
parser.nextTag("Log");
char *c;
parser.stream->read(c,3);
cout << c << endl;
return 0;
}
I have figured out that the program crashes when the fifth line of the main function [parser.stream->read(c,3);] is executed.
I wonder why this happens?
The char pointer you pass to ifstream::read is not initialized and thus points to an invalid memory region, causing your program to crash. You need it to point to a buffer you allocated:
int main(){
XMLParser parser("test.xml");
cout << "ready\n";
parser.nextTag("Log");
char c[3];
parser.stream->read(c,3);
cout << c << endl;
return 0;
}

No output when merge function is called

I have a doubt in the following code. Can somebody please explain.
using namespace std;
#define INT_SIZE 32
#define R 4
#define C 4
#define N 4
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<stack>
#include<vector>
#include<algorithm>
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2)
{
return (i1.start < i2.start)? true: false;
}
int merge(vector<interval>& a, int n)
{
stack<interval> s;
sort(a.begin(), a.end(), compareInterval);
s.push(a[0]);
int i=1;
interval temp;
while(i<n)
{
temp = s.top();
s.pop();
if(temp.end > a[i].start && a[i].end > temp.end)
{
temp.end = a[i].end;
s.push(temp);
}
else if(temp.end < a[i].start)
{
s.push(temp);
s.push(a[i]);
}
i++;
}
while(s.size())
{
temp = s.top();
cout << temp.start << " ";
cout << temp.end << "\n";
s.pop();
}
return 0;
}
int main()
{
interval intvls[] = { {6,8}, {1,9}, {2,4}, {4,7} };
vector<interval> intervals(intvls, intvls+4);
for(int i=0;i<4;i++)
{cout << intervals[i].start;
} // This output is not coming when merge function is called
cout << merge(intervals, 4);
}
My doubt is "When I comment the merge function call i.e
// cout << merge(intervals, 4);
When I comment this line, then I am able to see output of cout<<intervals[i].start.
Otherwise, I am not able to see the output.
"
You are not ending your output with a newline. Try:
{cout << intervals[i].start << "\n";}
Without the newline, this output is probably getting hidden amongst all the output produced by merge().
There are few issues with this code.
s.push(a[0]); <-- Only on element is in you stack.
//s.push(a[1]).. you will have to add all other elements like this.
while(i<n)
{
temp = s.top(); <-- for second i s will be empty. Here you must check if stack is empty before getting top element.
s.pop();
}
Your first output is not printed correctly. use std::endl
cout << intervals[i].start << endl;
There is a bug in merge that leads to a segmentation fault. Due to this std::cout is not flushed. If you comment out the line with the merge call, std::cout is flushed when the program exits.

Access violating writing location (visual studio 2008) Code based on pointers

The main problem is after sem->i = a; is used when yylex is called and c isalpha
sem->s[i] = c; doesn't work because sem->s[i] has an issue with the adress it points to.
more details:
So what i want to do is to open a txt and read what it is inside until the end of file.
If it's an alfanumeric (example: hello ,example2 hello45a) at the function yylex i put each of the characters into an array(sem->s[i]) until i find end of file or something not alfanumeric.
If it's a digit (example: 5234254 example2: 5) at the function yylex i put each of the characters into the array arithmoi[]. and after with attoi i put the number into the sem->i.
If i delete the else if(isdigit(c)) part at yylex it works(if every word in the txt doesn't start with a digit) .
Anyway the thing is that it works great when it finds only words that starts with characters. Then if it finds number(it uses the elseif(isdigit(c) part) it still works...until it finds a words starting with a character. when that happens there is an access violating writing location and the problem seems to be where i have an arrow. if you can help me i would be really thankfull.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <iostream>
using namespace std;
union SEMANTIC_INFO
{
int i;
char *s;
};
int yylex(FILE *fpointer, SEMANTIC_INFO *sem)
{
char c;
int i=0;
int j=0;
c = fgetc (fpointer);
while(c != EOF)
{
if(isalpha(c))
{
do
{
sem->s[i] = c;//the problem is here... <-------------------
c = fgetc(fpointer);
i++;
}while(isalnum(c));
return 1;
}
else if(isdigit(c))
{
char arithmoi[20];
do
{
arithmoi[j] = c;
j++;
c = fgetc(fpointer);
}while(isdigit(c));
sem->i = atoi(arithmoi); //when this is used the sem->s[i] in if(isalpha) doesn't work
return 2;
}
}
cout << "end of file" << endl;
return 0;
}
int main()
{
int i,k;
char c[20];
int counter1 = 0;
int counter2 = 0;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
SEMANTIC_INFO sematic;
SEMANTIC_INFO *sema = &sematic;
sematic.s = c;
FILE *pFile;
pFile = fopen ("piri.txt", "r");
do
{
k = yylex( pFile, sema);
if(k == 1)
{
counter1++;
cout << "it's type is alfanumeric and it's: ";
for(i=0; i<20; i++)
{
cout << sematic.s[i] << " " ;
}
cout <<endl;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
}
else if(k==2)
{
counter2++;
cout << "it's type is digit and it's: "<< sematic.i << endl;
}
}while(k != 0);
cout<<"the alfanumeric are : " << counter1 << endl;
cout<<"the digits are: " << counter2 << endl;
fclose (pFile);
system("pause");
return 0;
}
This line in main is creating an uninitialized SEMANTIC_INFO
SEMANTIC_INFO sematic;
The value of integer sematic.i is unknown.
The value of pointer sematic.s is unknown.
You then try to write to sematic.s[0]. You're hoping that sematic.s points to writable memory, large enough to hold the contents of that file, but you haven't made it point to anything.

exception_handling_C++_xcode

The following code throws the exception perfectly fine in Visual Studio 2010:
#include <iostream>
#include <cmath>
using namespace std;
int perfectSquare(double sq, int nu);
int main()
{
double num;
double squareRoot;
int perfectSq;
cout << "Enter the a number: ";
cin >> num;
try
{
squareRoot = sqrt(num);
perfectSq = perfectSquare(squareRoot, num);
cout << "The square root is: " << perfectSq << endl;
}
catch(char * exceptionString)
{
cout << exceptionString;
}
cout << "BYE." << endl;
// system("PAUSE");
return 0;
}
int perfectSquare(double sq, int nu)
{
int temp = sq;
if (sq != temp) //clever test; if square root IS NOT an INT
{
throw "not a perfect square.\n";
}
else
{
return sq;
}
}
However, in Xcode, it will not resume and it keeps hitting a breakpoint in the debugger. For example if I inpute 33 (not a perfect square), the following error is displayed:
libc++abi.dylib: terminate called throwing an exception
(lldb)
It should "throw" this line: "not a perfect square." and the program should terminate (like in VS 2010). I don't want to enable exception breakpoints in Xcode as I just want the program to run all the way to the end without debugging.
Thanks to all.
What you are throwing is a string literal, which in XCode seems to be a const char*, not a char*
You are not actually throwing a char *, you are throwing a const char *. Change the exception catch to
catch(const char * exceptionString)
and it should work.
All literal strings in C++ are equivalent to pointers to a constant string, i.e. const char *.