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 *.
Related
I wrote this code to check the exceptions I learned in a video, and now I tried to make the cube of an integer and if the entered number is not an integer I want the exception to be announced to the user.
#include <iostream>
float cube( float x)
{
char ch;
std::cin.get(ch);
if(ch=='.')
throw "Should be an integrer";
float cube=x*x*x;
return cube;
}
int main ()
{
float x;
std::cout<<" Enter an integrer : ";
std::cin>>x;
float cube_x=cube(x);
std::cout<<"Cube("<<x<<")="<<cube_x<<std::endl;
return 0;
}
You can use boost lexical-cast which is exactly for this purpose. It will throw an exception the conversion fails. Boost is well tested and you can safly use it to do the conversion for you.
This could look like this:
#include <boost/lexical_cast.hpp>
#include <iostream>
int cube(int x)
{
return x*x*x;
}
int main()
{
std::string x;
std::cout << " Enter an integrer : ";
std::cin >> x;
try
{
int y = boost::lexical_cast<int>(x);
int cube_x = cube(y);
std::cout << "Cube(" << x << ")=" << cube_x << std::endl;
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << e.what() << '\n';
}
return 0;
}
By the way, if your program shall only handle integers, you should also use type int and not float to handle the numbers.
Add the following to your source code:
#include <math.h> /* round, floor, ceil, trunc */
...
if (x == round(x)) {
...
}
Explanation can be found here: C++ Reference
I tried compiling this code being absolutely sure it won't compile since I try to modify the address to a const pointer (int p[100]), but the code compiled and run perfectly. Can anyone explain to me why this worked?
#include <iostream>
using namespace std;
int bar1(int *p){ cout << p << " "; p++; cout << p << "\n"; return 0; }
int bar2(int p[100]){ cout << p << " "; p++; cout << p; return 0; }
int arr1[100];
int arr2[100];
int main(){
bar1(arr1);
bar2(arr2);
}
I compiled this in Visual Studio 2013 the output was:
3f320 3f324
3f4B0 3f4B4
I try to modify the address to a const pointer (int p[100])
That's not a const pointer. As a function parameter, it's equivalent to int * p.
A const pointer looks like int * const p, and your code will give the expected compile error if you use that.
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;
}
Please can you check this code? What's wrong with try/catch/throw?
#include<iostream>
using namespace std;
int get_input();
int main() {
int number, base_in, base_out;
bool pass = 1;
while(pass) {
double number, base_in, base_out;
try {
cout << "What's your number? ";
number = get_input();
pass = 0;
}
catch(problem_type()) {
cout << "Please, write inputs should be integer" << endl;
}
}
return 0;
}
int get_input(bool target = 1) {
double n;
cin >> n;
if(n != (int)n) throw problem_type();
if(target) {
if(n<1) throw problem_type();
}
return (int)n;
}
You catch by type. Like
catch(const problem_type&){ }
That is, if problem_type is type. I see no definition anywhere…
When an exception is throw you'll get a in memory object with info about the exception... so it's necessary to take it as catch( const Type& error )
Why is it as a reference? Think of the possible caotic state that would be on memory on some situations, so MAKE a copy of would add complications and processing time, you could loose vital info. So that's why we take it as a reference.
Just 'point' to original piece of data.
I basically have exp>=level*10 in an else if expression, where level is a variable and 10 is a constant number. The code compiles completely fine without any errors, and it even worked after being compiled, until recently. now, whenever it compiles and executes, it gives me an error saying "invalid null pointer" and it conveniently tells me that the problem comes from the included file xstring (VS2010 includes it in new projects) on line 930.
Is there a way to force to program to read it as the multiplication operator instead of a null pointer?
EDIT: Here is my full code, please note that this is a protype created to ensure that it will work and was done prior to me realizing I can use derived classes for this. also note that I tried removing using namespace std to see if that was the problem.
#include "stdafx.h"
#include <iostream>
#include <sstream>
class player {
public:
std::string name;
int hp;
int attack;
int strength;
int defense;
void reward(int gold, int exp) {
player::gold += gold;
player::exp += exp;
player::levelHandler();
}
int dataQuery(std::string query) {
if (query == "equipment")
return helm, armour, greaves;
else if (query == "gold")
return gold;
else if (query == "exp")
return exp;
else if (query == "level")
return level;
else return 0;
}
private:
int helm;
int armour;
int greaves;
int level;
int gold;
int exp;
std::string levelHandler() {
if (level==0) {
level=1;
}
else if (exp>=(10*level)) { //causes problem due to * being mistaken as a
//null pointer.
int previousLevel = level;
level += 1;
levelHandler();
return 0;
};
return 0;
};
} hero;
class enemy {
public:
std::string name;
int hp;
int attack;
int strength;
int defense;
private:
int helm;
int armour;
int greaves;
int level;
int goldReward;
int expReward;
int dataQuery(std::string query) {
if (query == "equipment")
return helm, armour, greaves;
else if (query == "gold")
return goldReward;
else if (query == "exp")
return expReward;
else if (query == "level")
return level;
else return 0;
}
};
int main()
{
std::cout << "Please enter your character's name..." << std::endl;
std::cin >> hero.name;
std::cout << "Welcome to RPG Battle Simulation, " << hero.name << "!" << std::endl;
hero.reward(100, 0); //problem is either this line, or the function's call to levelHandler, as this is where the program terminates.
std::cout << "You are beginning your journey as a level " << hero.dataQuery("level") << " character." << std::endl;
std::cout << "Here is " << hero.dataQuery("gold") << " gold to get you started." << std::endl;
return 0;
};
The following is an excerpt of xstring that is causing the problem. the problem comes from _DEBUG_POINTER(_Ptr); (line 930)
_Myt& assign(const _Elem *_Ptr)
{// assign [_Ptr, <null>)
_DEBUG_POINTER(_Ptr);
return (assign(_Ptr, _Traits::length(_Ptr)));
}
This program reproduces your problem (when compiled with MSVC with runtime that supports debugging):
#include <string>
#include <iostream>
int main()
{
using namespace std;
string s = 0;
cout << s << endl;
}
The problem is that a std::string is initialized with a nullpointer.
EDIT: oh, forgot to mention, solution – simply don’t do that.
Cheers & hth.,