Unterminating c++ Program [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have recently read an enormous book on c++, but I have not tested what I have learned until now. Now, this "enormous book" of mine was actually made in 1995, so I obviously cannot trust everything that this book states. In other words, I know not whether the compiler, enormous book, or I did something wrong.
In order to test my knowledge of c++, I made a class (without pointer syntax due to fear of potential disaster) that I called MathContext. As a quick summary, this class of mine has eight (!) constructors in order to be user-friendly (if I can get this to work). It has three private fields (or attributes; I know not what one would prefer to call them in c++) called base, precision, and mode. The base field of type short stores the requested base (from two, inclusive, to thirty-six, inclusive), the precision field stores the requested decimal digit count (according to the base; I'll worry about that later), and the mode field is actually an instance of a nested enumeration called RoundingMode.
As you may see, this class is somewhat similar to the java.math.MathContext class except that I include the "java.math.RoundingMode" enumeration within the "java.math.MathContext" class.
Here is the complete syntax of all files that I have written in order to test this MathContext class:
MathContext.h:
#pragma once
class MathContext sealed
{
public:
enum RoundingMode
{
DOWN,
UP,
FLOOR,
CEILING,
HALF_DOWN,
HALF_UP,
HALF_EVEN
};
MathContext(void);
MathContext(unsigned short);
MathContext(unsigned int);
MathContext(RoundingMode);
MathContext(unsigned short, unsigned int);
MathContext(unsigned short, RoundingMode);
MathContext(unsigned int, RoundingMode);
MathContext(unsigned short, unsigned int, RoundingMode);
~MathContext(void);
unsigned short get_base(void);
void set_base(unsigned short);
unsigned int get_precision(void);
void set_precision(unsigned int);
RoundingMode get_rounding_mode(void);
void set_rounding_mode(RoundingMode);
bool operator==(MathContext);
bool operator!=(MathContext);
bool operator>(MathContext);
bool operator<(MathContext);
bool operator>=(MathContext);
bool operator<=(MathContext);
private:
unsigned short base;
unsigned int precision;
unsigned RoundingMode mode;
}
MathContext.cpp:
#include "stdafx.h"
#include "MathContext.h"
MathContext::MathContext(void)
{
base = 10;
precision = 15;
mode = RoundingMode::HALF_EVEN;
}
MathContext::MathContext(unsigned short base)
{
set_base(base);
precision = 15;
mode = RoundingMode::HALF_EVEN;
}
MathContext::MathContext(unsigned int precision)
{
base = 10;
set_precision(precision);
mode = RoundingMode::HALF_EVEN;
}
MathContext::MathContext(RoundingMode rounding_mode)
{
base = 10;
precision = 15;
mode = rounding_mode;
}
MathContext::MathContext(unsigned short base, unsigned int precision)
{
set_base(base);
set_precision(precision);
mode = RoundingMode::HALF_EVEN;
}
MathContext::MathContext(unsigned short base, RoundingMode rounding_mode)
{
set_base(base);
precision = 15;
mode = rounding_mode;
}
MathContext::MathContext(unsigned int precision, RoundingMode rounding_mode)
{
base = 10;
set_precision(precision);
mode = rounding_mode;
}
MathContext::MathContext(unsigned short base, unsigned int precision, RoundingMode rounding_mode)
{
set_base(base);
set_precision(precision);
mode = rounding_mode;
}
MathContext::~MathContext(void)
{
delete &base;
delete &precision;
delete &mode;
}
unsigned short MathContext::get_base(void)
{
return base;
}
void MathContext::set_base(unsigned short value)
{
base = value == 0 || value % 36 == 1 ? 2 : (value % 36 == 0 ? 36 : value % 36);
}
unsigned int MathContext::get_precision(void)
{
return precision;
}
void MathContext::set_precision(unsigned int value)
{
precision = value;
}
MathContext::RoundingMode MathContext::get_rounding_mode(void)
{
return mode;
}
void MathContext::set_rounding_mode(RoundingMode rounding_mode)
{
mode = rounding_mode;
}
bool MathContext::operator==(MathContext context)
{
return base == context.base && precision == context.precision && mode == context.mode;
}
bool MathContext::operator!=(MathContext context)
{
return base != context.base || precision != context.precision || mode != context.mode;
}
bool MathContext::operator>(MathContext context)
{
return precision == context.precision ? mode > context.mode : precision > context.precision;
}
bool MathContext::operator<(MathContext context)
{
return precision == context.precision ? mode < context.mode : precision < context.precision;
}
bool MathContext::operator>=(MathContext context)
{
return precision == context.precision ? mode >= context.mode : precision > context.precision;
}
bool MathContext::operator<=(MathContext context)
{
return precision == context.precision ? mode <= context.mode : precision < context.precision;
}
Graphics.cpp (the test class; please don't ask why I called it that):
#include "stdafx.h"
#include "MathContext.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
MathContext context[8];
context[0] = MathContext::MathContext();
context[1] = MathContext::MathContext((unsigned short) 46);
context[2] = MathContext::MathContext((unsigned int) 20);
context[3] = MathContext::MathContext(MathContext::RoundingMode::UP);
context[4] = MathContext::MathContext((unsigned short) 36, (unsigned int) 30);
context[5] = MathContext::MathContext((unsigned short) 36, MathContext::RoundingMode::HALF_DOWN);
context[6] = MathContext::MathContext((unsigned int) 25, MathContext::RoundingMode::HALF_EVEN);
context[7] = MathContext::MathContext((unsigned short) 26, (unsigned int) 29, MathContext::RoundingMode::HALF_EVEN);
int best = 0;
for(int i = 1; i < 8; i++)
{
if(context[best] < context[i])
{
best = i;
}
}
std::cout << "Context #" << best + 1 << " is the best!\n";
return 0;
}
I hoped that, Context #5 is the best! would show on the console (my Windows 8.1 Command Prompt), but I could not get anywhere near that point because after I compiled those three files and began to debug them, the command prompt actually did not terminate (I assume that some would call it a freeze), so I had to force its exit through the Windows 8.1 Task Manager. Now, that's what I call a problem!
Here are two essential details: My OS is Windows 8.1 (I hope that it won't throw anyone off), and I use the Microsoft Visual Studio Express 2012 for Windows Desktop Update 4. As miscellaneous information, I consider myself as an expert Java programmer (it may or may not help; perhaps someone could point out some relevant differences between Java and c++ so that this won't happen ever again), and the source code that I typed actually removed unnecessary whitespace; for example, instead of base = 10;, I typed base=10; Well, the compiler apparently thinks that my code is fine, but it apparently is not for some reason. Could anyone point out to me what is obsolete that I use, why the debugging apparently freezes the command prompt, and any essential differences between Java and c++ that I should take note of as I program in c++? I sincerely thank you!

You are calling the MathContext constructor-methods directly, change that to to the below
by dropping the first part of MathContext::MathContext to just MathContext
int main(int argc, _TCHAR* argv[])
{
MathContext context[8];
context[0] = MathContext();
context[1] = MathContext((unsigned short) 46);
context[2] = MathContext((unsigned int) 20);
context[3] = MathContext(MathContext::UP);
context[4] = MathContext((unsigned short) 36, (unsigned int) 30);
context[5] = MathContext((unsigned short) 36, MathContext::HALF_DOWN);
context[6] = MathContext((unsigned int) 25, MathContext::HALF_EVEN);
context[7] = MathContext((unsigned short) 26, (unsigned int) 29, MathContext::HALF_EVEN);
You are deleting memeory which is not allocated (newed) by you (remove that)
MathContext::~MathContext(void)
{
//delete &base;
//delete &precision;
//delete &mode;
}
In short, your program was hanging due to the weird memory errors you had -- direct invocation of a constructor will assume that memory for the object is already allocated + the deallocation of memory which you had not allocated.

Related

g++ optimization makes the program unable to run

I implemented a path planning algorithm based on D*-Lite. When I do not turn on optimization (-O0), the program can run normally. But when I turn on the optimization level (-O1/2/3), the program cannot be terminated. In Visual Studio, both debug mode and release mode can run normally. In the above cases, the codes are the same.I don’t know how to find the problem, can anyone help me?
class DstarLite {
public:
DstarLite() = delete;
DstarLite(GridStatus* a, GridStatus* b, FILE* fp)
: k_m_(0), start_(a), last_(start_), goal_(b), open_close_(fp) {}
void calculateKey(GridStatus* s);
void updateVertex(GridStatus* u);
void initialize();
void computeShortestPath();
void rePlanning(vector<pair<GridStatus*, int>>& node_change);
GridStatus* getStart();
void setStart(GridStatus* val);
GridStatus* getGoal();
private:
Fib frontier_;
double k_m_;
unordered_map<GridStatus*, handle_t>
heap_map_;
GridStatus* start_;
GridStatus* last_;
GridStatus* goal_;
FILE* open_close_;
};
void DstarLite::calculateKey(GridStatus* s) {
s->f = min(s->g, s->rhs) + heuristic(start_, s) + k_m_;
s->k2 = min(s->g, s->rhs);
}
void DstarLite::initialize() {
fprintf(open_close_, "%d %d\n", start_->x, start_->y);
fprintf(open_close_, "%d %d\n", goal_->x, goal_->y);
goal_->rhs = 0;
calculateKey(goal_);
handle_t hand = frontier_.push(goal_);
heap_map_[goal_] = hand;
}
void DstarLite::updateVertex(GridStatus* u) {
bool heap_in = heap_map_.find(u) != heap_map_.end();
if (u->g != u->rhs && heap_in) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (u->g != u->rhs && !heap_in) {
calculateKey(u);
handle_t hand = frontier_.push(u);
heap_map_[u] = hand;
} else if (u->g == u->rhs && heap_in) {
calculateKey(u);
frontier_.erase(heap_map_[u]);
heap_map_.erase(u);
}
}
void DstarLite::computeShortestPath() {
int count = 0;
while (smaller(frontier_.top(), start_) || !myEqual(start_->rhs, start_->g)) {
count++;
auto u = frontier_.top();
pair<double, double> k_old = {u->f, u->k2};
pair<double, double> k_new;
k_new.first = min(u->g, u->rhs) + heuristic(start_, u) + k_m_;
k_new.second = min(u->g, u->rhs);
if (k_old < k_new) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (myGreater(u->g, u->rhs)) {
u->g = u->rhs;
frontier_.pop();
heap_map_.erase(u);
for (auto s : neighbors(u)) {
if (s->rhs > u->g + cost(u, s)) {
s->next = u;
s->rhs = u->g + cost(u, s);
updateVertex(s);
}
}
} else {
double g_old = u->g;
u->g = kDoubleInfinity;
auto neighbor = neighbors(u);
neighbor.push_back(u);
for (auto s : neighbor) {
if (myEqual(s->rhs, cost(s, u) + g_old)) {
if (!equal(s, goal_)) {
double pp_s = kDoubleInfinity;
for (auto succ : neighbors(s)) {
double dis = succ->g + cost(succ, s);
if (dis < pp_s) {
pp_s = dis;
s->next = succ;
}
}
s->rhs = pp_s;
}
}
updateVertex(s);
}
}
}
cout << "Dstar visited nodes : " << count << endl;
}
void DstarLite::rePlanning(vector<pair<GridStatus*, int>>& node_change) {
k_m_ += heuristic(last_, start_);
last_ = start_;
for (auto change : node_change) {
GridStatus* u = change.first;
int old_threat = u->threat;
int new_threat = change.second;
double c_old;
double c_new;
u->threat = new_threat;
u->rhs += (new_threat - old_threat) * threat_factor;
updateVertex(u);
for (auto v : neighbors(u)) {
u->threat = old_threat;
c_old = cost(v, u);
u->threat = new_threat;
c_new = cost(v, u);
if (c_old > c_new) {
if (v != goal_) {
if (v->rhs > u->g + c_new) {
v->next = u;
v->rhs = u->g + c_new;
}
}
} else if (myEqual(v->rhs, c_old + u->g)) {
if (v != goal_) {
double pp_s = kDoubleInfinity;
for (auto pre : neighbors(v)) {
double dis = pre->g + cost(pre, v);
if (dis < pp_s) {
pp_s = dis;
v->next = pre;
}
}
v->rhs = pp_s;
}
}
updateVertex(v);
}
}
}
GridStatus* DstarLite::getStart() { return start_; }
void DstarLite::setStart(GridStatus* val) { start_ = val; }
GridStatus* DstarLite::getGoal() { return goal_; }
DstarLite dstar(start, goal, open_close);
dstar.initialize();
dstar.computeShortestPath();
Sorry, I think it is difficult to locate the problem in the code, so the code was not shown before. Now I have re-edited the question, but there are a lot of codes, and the main calling part is computeShortest().
As you did not provide any code, we can give you only some general hints to fix such problems.
As a first assumption your code has definitely one or more bugs which causes what we call undefined behaviour UB. As the result is undefined, it can be anything and is often changing behaviour with different optimization levels, compiler versions or platforms.
What you can do:
enable really ALL warnings and fix them all! Look especially for something like "comparison is always...", "use of xxx (sometimes) without initialization", " invalid pointer cast", ...
try to compile on different compilers. You should also try to use gcc and/or clang, even on windows. It is maybe hard in the first time to get the environment for these compilers run on windows plattforms, but it is really worth to do it. Different compilers will give different warnings. Fixing all warnings from all compilers is a really good help!
you should use memory tracers like valgrind. I have not much experience on windows, but I believe there are also such tools, maybe already integrated in your development suite. These tools are really good in finding "of by x" access, access freed memory and such problems.
if you still run into such trouble, static code analyser tools may help. Typically not as much as managers believe, because today's compilers are much better by detecting flaws as expected by dinosaur programmers. The additional findings are often false positives, especially if you use modern C++. Typically you can save the money and take a class for your own education!
Review, Review, Review with other people!
snip the problem small! You should spend most of your development time by setting up good automated unit tests. Check every path, every function in every file. It is good to see at minimum 95% of all branches covered by tests. Typically these tests will also fail if you have UB in your code if you change optimizer levels and or compiler and platforms.
using a debugger can be frustrating. In high optimized code you jump through all and nothing and you may not really see where you are and what is the relation to your code. And if in lower optimizer level the bug is not present, you have not really much chance to see find the underlying problem.
last but not least: "printf debugging". But this may change the behaviour also. In worst case the code will run always if you add a debug output. But it is a chance!
use thread and memory sanitizers from your compiler.
The problem is caused by the comparison of floating-point numbers. I deliberately put aside this question when I wrote the code before :). Now it can operate normally after being fixed.

How do I enumerate volumes on MacOSX in C++?

I'm brand new to Mac development/xcode. I'm trying to do what I feel should be extremely simple, but over a week of research has yielded no results.
I want to list the external usb drive available as a vector of strings.
I don't want their cryptic information like address serial or anything. I just want their paths IE: "D:/" or "Sandisk USB".
I accomplished this in Windows quite easily using the code found below, but finding out how to do this on Mac has me pulling my hair out.
The only thing I've found seems to be done for Objective C, - How to enumerate volumes on Mac OS X?
but my project uses c++.
Can someone please provide a simple example or point me in the right direction.
struct ESDriveDescription
{
std::string path;
std::string label;
ESDriveDescription() = default;
ESDriveDescription(const std::string &path, const std::string &label)
: path(path), label(label)
{}
};
int ESFileUtils::getExternalStorageDevicePaths(vector<ESDriveDescription> &paths){
// Letters in alphabet * 3 characters per drive path, + nul term + final nul
// NOTE: constexpr not supported in vs2013
static const DWORD DRIVE_BUFFER_SIZE = 26 * 4 + 1;
static const DWORD VOLUME_LABEL_MAX = 32;
const char* removableDriveNames[26] = { 0 };
char allDrives[DRIVE_BUFFER_SIZE] = { 0 };
int numRemovableDrives = 0;
DWORD n = GetLogicalDriveStringsA(DRIVE_BUFFER_SIZE, allDrives);
for (DWORD i = 0; i < n; i += 4) {
const char* driveName = &allDrives[i];
UINT type = GetDriveTypeA(driveName);
if (type == DRIVE_REMOVABLE)
removableDriveNames[numRemovableDrives++] = driveName;
}
char label[VOLUME_LABEL_MAX] = { 0 };
for (int i = 0; i < numRemovableDrives; i++) {
const char* driveName = removableDriveNames[i];
GetVolumeInformationA(driveName, label, VOLUME_LABEL_MAX, 0, 0, 0, 0, 0);
paths.emplace_back(driveName, label);
}
return numRemovableDrives;
}

Arduino class implementing TimeLib.h

I'm creating this library for the ESP8266-Arduino that makes use of the TimeLib.h library.
In my header I have:
WiFiUDP *_UdpNTP = NULL;
void setupTime();
time_t getNtpTime();
void sendNTPpacket(WiFiUDP *u);
And these are my functions:
void Konnec::setupTime() {
setSyncProvider(getNtpTime);
setSyncInterval(NTP_POL_TIME);
}
time_t Konnec::getNtpTime() {
//WiFiUDP udp;
//udp.begin(localPort);
_UdpNTP = new WiFiUDP();
_UdpNTP->begin(localPort);
while (_UdpNTP->parsePacket() > 0); // discard any previously received packets
for (int i = 0; i < 5; i++) { // 5 retries.
sendNTPpacket(_UdpNTP);
uint32_t beginWait = millis();
while (millis() - beginWait < 1000) {
if (_UdpNTP->parsePacket()) {
Serial.println("");
Serial.println("Receive NTP Response");
_UdpNTP->read(packetBuffer, NTP_PACKET_SIZE);
// Extract seconds portion.
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secSince1900 = highWord << 16 | lowWord;
_UdpNTP->flush();
return secSince1900 - 2208988800UL + TIMEZONE * SECS_PER_HOUR;
}
delay(10);
}
}
Serial.println("");
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}
void Konnec::sendNTPpacket(WiFiUDP *u) {
// Zeroise the buffer.
memset(packetBuffer, 0, NTP_PACKET_SIZE);
memcpy(packetBuffer, sendBuffer, 16);
if (u->beginPacket(timeServer, 123)) {
u->write(packetBuffer, NTP_PACKET_SIZE);
u->endPacket();
}
}
And this is the error I get:
konnec.cpp: 991:28: error: cannot convert 'Konnec::getNtpTime' from type 'time_t (Konnec::)() {aka long int (Konnec::)()}' to type 'getExternalTime {aka long int (*)()}
setSyncProvider(getNtpTime)
Error compiling libraries
Any knows what would be the solution?
The problem seems to be that Konnec::getNtpTime is a class method, and yet setSyncProvider expects a function. A function and a method are different things remember, as a method also needs to know the specific class instance it is operating on.
Looking through your code though, it looks like getNtpTime doesn't rely on anything specific to your class, so you could declare it as:
static time_t Konnec::getNtpTime();
which will let it be used as a function, as it effectively is at that point.

How to do arithmetic operation on very large numbers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to add several 50-digit numbers from an array of strings and print first 10 digit of the summation,but I am getting the wrong answer.What is wrong with my code?
The answer should be: 5537376230
My answer is :3737623039
p.s. i have used the array to store single digits of the summation
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string num[100] = {
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690",
};
long long sum[100];
int runner=0;
long long carry=0;
for(int l=49;l>=0;l--)
{
int total=0;
for(int k=0;k<100;k++ )
{
total+=(int)num[k][l]-48;
}
total=total+carry;
sum[runner]=total%10;
if(total>9)carry=total/10;
else carry=0;
runner++;
}
//cout<<runner<<endl;
for(int l=runner-1;l>runner-11;l--)
{
cout<<sum[l];
}
}
After your last loop, the carry is 55, but you never insert it into the result.
Since you only need the first 10 digits
int main(int argc, char **argv)
{
int i;
char *num[100] = {
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690",
};
long int sum = 0;
for (i = 0 ; i < 100 ; i++)
{
char firstDigits[15];
memcpy(firstDigits, num[i], 14);
firstDigits[14] = 0;
sum += strtol(firstDigits, NULL, 10);
}
char string[11];
snprintf(string, 11, "%ld", sum);
fprintf(stderr, "%s\n", string);
return 0;
}
I don't know if this is the only problem, but you are using 'int' which has the following range:
–2,147,483,648 to 2,147,483,647
Your numbers are to big and will therefore not work as desired.
Check http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx to se the available data-types
You're implicitly assuming that the answer will have no more digits than each of the inputs, which clearly doesn't hold in this case. You do allocate 100 digits for the output, which is more than sufficient, but you never fill more than 50 of them. I've had a go at modifying your code to remedy this.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int nnum = 100, idigits = 50, odigits = 100;
string num[nnum] = {
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690",
};
int sum[odigits];
int carry=0, d;
for(d=0;d<odigits;d++)
{
int ipos = idigits-1-d;
int opos = odigits-1-d;
int total = carry;
if(ipos >= 0)
for(int k = 0; k < nnum; k++)
total += num[k][ipos]-48;
else if(carry == 0) break;
sum[opos] = total%10;
carry = total/10;
}
for(int i=0; i < 10; i++)
cout << sum[odigits-d+i];
cout << "\n";
}
This produces the desired result 5537376230.
Since an int can hold much more than just 1 decimal digit, a more efficient approach would be to process larger groups of digits at once.

NLOpt with windows forms

I am suffering serious problems while trying to use nlopt library (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) in windows forms application. I have created following namespace which runs perfectly in console application.
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
It optimizes simple nonlinear constrained minimization problem. The problem arises when I try to use this namespace in windows form application. I am constantly getting unhandled exception in myfunc which sees "x" as empty pointer for some reason and therefore causes error when trying to access its location. I believe that the problem is somehow caused by the fact that windows forms uses CLR but I dont know if it is solvable or not. I am using visual studio 2008 and the test programs are simple console project (which works fine) and windows forms project (that causes aforementioned errors).
My test code is based on tutorial for C from the provided link. I although tried C++ version which once again works fine in console application but gives debug assertion failed error in windows forms application.
So I guess my questions is : I have working windows forms application and I would like to use NLOpt. Is there a way to make this work ?