Addition Operation from ints in a String - c++

I set up a string filled solely with numbers and using a for loop iterated through it in order to add them together mathematically (Wanted to see if the language would allow this), as a result I got some weird Numbers as the result. Can someone explain why this is happening?
int main()
{
std::string word = "2355412";
for (int i = 0; i<word.size(); i++){
int sum = word[i]+word[i+1];
std::cout << sum << std::endl;
}
return 0;
}
The code when run results in:
101
104
106
105
101
99
50
Due to the way I wrote my code I also believe that it should have resulted in an out of bounds error due word[i+1] on the final value resulting in the calling of a value that does not exist. Can someone explain why it did not throw an error?

The value you get is not what you expect because it is the sum of the ascii code corresponding to the characters you are summing, it's not converted into their value by default.
Also, as mentioned by other, string::operator[] doesn't check if you are trying to reach an out of bound value. In this case, you read 0 because you reached the string termination character \0 which happen to be 0.

it should have resulted in an out of bounds error
string::operator[] doesn't check bounds, it assumes you have. If you call it with an out of bounds index, the entire behaviour of your program is undefined, i.e. anything can happen.
It sounds like you want string::at, which does check bounds, and will throw std::out_of_range

Related

C++ program crashes at delete only when character array gets the input of "1000!"

I wrote a quick and dirty factorial program using the GMP library in C++, which allocates some memory for a character array. The program works fine for all input values that I've tested, except 1000.
I've tried different ways to allocate the memory, and different ways to deallocate it, but none have worked so far and almost always crash on 1000.
This is everything that happens between creating the character array and deleting it. factor is the calculated factorial and mpz_sizeinbase returns the number of digits in the number in the specified base. gmp_sprintf just transforms the number into the character array.
int count = mpz_sizeinbase(factor, 10);
char* zeroes = new char[count];
gmp_sprintf(zeroes, "%Zd", factor);
printf("After conversion: %s\n", zeroes);
int trailingzeroes = 0;
for(int i = strlen(zeroes)-1; i > 0; i--){
if(zeroes[i] == '0')
trailingzeroes++;
else
break;
}
printf("Trailing zeroes: %i\n", trailingzeroes);
delete [] zeroes;
When the input is 1000, meaning that I want to calculate 1000!, I get the error
double free or corruption (!prev)
Aborted
at delete [].
All other inputs work, as far as I can tell.
What could I be doing wrong?
From the mpz_sizeinbase documentation: "The right amount of allocation is normally two more than the value returned by mpz_sizeinbase, one extra for a minus sign and one for the null-terminator." You probably don't have a negative factorial, but you are certainly not allocating enough space for including the terminating null character.
It would be instructive to check the return value of gmp_sprintf because it tells you how many characters it actually wrote. I would wager that in your case it returns count+1, which would mean it wrote past the end of the buffer (which is Undefined Behavior).
The fact that it sometimes might work is probably related to the fact that "the result will be either exact or 1 too big" (for bases other than 2). That and of course the unpredictable nature of UB.

Strangely For loop counter variable gets reduced by .get()

Consider the following piece of code. This function reads the some integers and strings from a file.
const int vardo_ilgis = 10;
void skaityti(int &n, int &m, int &tiriama, avys A[])
{
ifstream fd("test.txt");
fd >> n >> m >> tiriama;
fd.ignore(80, '\n');
char vard[vardo_ilgis]; // <---
for(int i = 1; i <= n; i++)
{
cout << i << ' ';
fd.get(vard, vardo_ilgis+1); // <---
cout << i << endl;
A[i].vardas = vard;
getline(fd, A[i].DNR);
}
fd.close();
}
and input:
4 6
4
Baltukas TAGCTT
Bailioji ATGCAA
Doli AGGCTC
Smarkuolis AATGAA
In this case, variable 'vard' has a length vardo_ilgis = 10, but in function fd.get the read input is vardo_ilgis+1 = 11 (larger than the variable length in which data is stored). I'm not asking how to fix a problem, because it's obvious not to read more than you can store on a variable.
However, I really want to understand the reason of this behaviour: the loop count variable gets decreased by fd.get. Why and how even can this happen? That's the output of this little piece of code:
1 0
1 0
1 0
1 0
1 1
2 2
3 3
4 4
Why did you use +1 ??
fd.get(vard, vardo_ilgis+1);
Overrunning that buffer corrupts some memory. In a simple unoptimized build, that corrupted memory could be the loop index.
the loop count variable gets decreased by fd.get. Why and how even can this happen?
Once you know why you have caused undefined behavior, many people say you aren't supposed to inquire into the details of that undefined behavior. I disagree. By understanding the details, you can improve your ability to diagnose other situations where you don't know what undefined behavior you might have invoked.
All you local variables are stored together, so overwriting one will tend to clobber another.
You describe the variable being "decreased" when in fact it was set to zero. The fact that it was 1 before being zeroed didn't affect its being zeroed. The undefined behavior happened to be equivalent to i&=~255; which for values under 256 is equal to i=0;. It is more accidental that you could see it as i--;
Hopefully it is clear why i stopped being zeroed once you ran out of input.
fd.get(vard, vardo_ilgis+1); makes buffer be written out-of-bounds.
In your case, the area where you write (and where you should not) is probably the same memory area where i is stored.
But, what's most important is that you end up with the so famous undetermined behaviour. Which mean anything could happen and there is no point trying to understand why or how (what happens is platform, compiler and even context specific, I don't think anyone can predict nor explain it).

error : Vector subscript out of range error

I have this code in c++ and I used vectors but I got this error:
error: Vector subscript out of range error.
Can some help me in this issue.
int const TN = 4;
vector <uint32_t> totalBytesReceived(TN);
void ReceivePacket(string context, Ptr <const Packet> p)
{
totalBytesReceived[context.at(10)] += p->GetSize();
}
void CalculateThroughput()
{
double mbs[TN];
for (int f = 0; f<TN; f++)
{
// mbs = ((totalBytesReceived*8.0)/100000);
mbs[f] = ((totalBytesReceived[f] * 8.0) / 100000);
//totalBytesReceived =0;
rdTrace << Simulator::Now().GetSeconds() << "\t" << mbs[f] << "\n";
Simulator::Schedule(Seconds(0.1), &CalculateThroughput);
}
}
It seems like
totalBytesReceived[context.at(10)] += p->GetSize();
throws the exception because the char at position 10 of context is out of range. Since you use it to index the vector, it has to be in the range 0 to 3.
Looking at the content of context you posted:
"/NodeList/" 1 "/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRx"
^ ^ ^
0 10 12
If you want to extract the 1 and use it as an index, you need to use:
char c = context.at(12); // Extract the char.
int index = c - '0'; // Convert the character '1' to the integer 1.
This is because of the ASCII standard which determines how characters are stored as numbers.
Probably the real issue is that you get the character '1' and use its ASCII value as index to the vector instead of the intended integer value 1.
This out of bounds access is then undefined behaviour, which in your case leads to an exception.
The following is not the cause, leaving it for reference:
The exception is probably coming from this expression:
context.at(10)
This is the only operation (*) involved that is actually performing bounds checking. The vector operator[] isn't doing that, neither does a C array check it's bounds.
So: Are you sure the string context is never shorter than 11 characters?
(*) Accessing a vector out of bounds is undefined behaviour, and throwing an exception is within the possible outcomes of that. Thanks to Beta Carotin and Benjamin Lindley for that.
This is the real thing:
Also note that a vector isn't resized like map when accessing an out of bounds index using operator[], so unless you can guarantee that the characters in the string are between 0 and 3 inclusive this will be your next issue.
And this means (size_t)0 and (size_t)3, not the characters '0' and '3'.

code blocks power function is not working in c

i am using code block for learning c. my code is
#include<stdio.h>
#include<math.h>
int main()
{
int x;
x = pow(5,2);
printf("%d", x);
}
Output is 25
When i am using this code
#include<stdio.h>
#include<math.h>
int main()
{
int x,i,j;
printf("please enter first value");
scanf("%d", &i);//5
printf("please enter second value");//2
scanf("%d", &j);
x = pow(i,j);
printf("%d", x);
}
Output is 24
what is wrong here? i am just taking value using scan function and also using pow function in a same way.
I suspect you have a naive implementation of pow in your libm (I get 25, as it should be). If that computes pow(x,y) as exp(y*log(x)) for positive x without checking for (small) integral exponents and treating them specially, you get
Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996
a double result slightly smaller than 25, so when that is converted to int it is truncated to 24.
To check, assign the result of pow(i,j) to a double and print that out.
With hardcoded pow(5,2), the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.
Try changing initialization to this:
int x=-1 ,i=-1 ,j=-1;
And last print to this:
printf("pow(%d, %d) == %d\n", i, j, x);
That should give good hint about the problem. Also, check return values of scanf, they should return number of items read, ie. 1 with code above.
It's almost certain, that you entered invalid input for scanf, and i or j were left uninitialized, and that 24 is just garbage value.
Also, compile with warnings enabled, and fix them (like, add return 0; to end of main).
Your code correctly gives 25 on my windows x64.
You probably needs to run it again see if you just read it wrong...
The missing "return 0;" is not the problem here.
If, anything, could ever go wrong,
you can try adding
fflush(stdin);//or out
after very scanf and printf.
If any of the flushes solves your problem, you know what is going wrong.
It seems that there is nothing wrong with the second program, except that you must add at the end
return 0;
If you read the value j with 2 then the result will be just 25.
Using your code i got result 25 which is correct.
Although Try changing the data type of result such as float or double.

Floating Point Exception C++ Why and what is it?

I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the number. Here's the code:
int main()
{
int input;
cout << "Enter number: " << endl;
cin>> input;
int i = input/2;
int c;
for (i>0; i--;) {
c= input%i;
if (c==0 || i == 1)
cout << "not prime" << endl;
else
cout << "prime" << endl;
}
return 0;
}
so essentially why is it giving me a floating point exception and what does that even mean?
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.