Terminate called after throwing an instance of std invalid argument what stoi

Terminate called after throwing an instance of std invalid argument what stoi

Download fails ‘std::invalid_argument’ what(): stoi #101

Comments

hollunder commented Jan 18, 2017 •

Happens with latest git and 3.1.
I also created fresh config, no difference.
Since both versions are affected I assume this is due to a change on gog.com.

The text was updated successfully, but these errors were encountered:

Sude- commented Jan 18, 2017

Backtrace from debug build would be helpful.

hollunder commented Jan 19, 2017 •

The text output is rather long and I have yet to sanitize it. Is there a specific part that you are looking for?

Sude- commented Jan 19, 2017 •

The text output is rather long and I have yet to sanitize it. Is there a specific part that you are looking for?

The last json output from it might be useful.

Run the debug build with gdb

after the downloader crashes type

Output from that backtrace command would be helpful

hollunder commented Jan 19, 2017

Hi, here is the requested output.

terminate called after throwing an instance of ‘std::invalid_argument’
what(): stoi

Thread 1 «lgogdownloader» received signal SIGABRT, Aborted.
0x00007ffff526a04f in raise () from /usr/lib/libc.so.6
(gdb) thread apply all bt

invalid_argument())
at /build/gcc/src/gcc/libstdc++-v3/libsupc++/eh_throw.cc:87
#6 0x00007ffff5ba8f8f in std::__throw_invalid_argument (__s=0x4b0d90 «stoi») at /build/gcc/src/gcc/libstdc++-v3/src/c++11/functexcept.cc:82
#7 0x0000000000450008 in int __gnu_cxx::__stoa (long ()(char const, char**, int), char const*, char const*, unsigned long*, int) ()
#8 0x0000000000466b44 in Website::getGames() ()
#9 0x00000000004749b4 in Downloader::getGameList() ()
#10 0x0000000000487acd in Downloader::listGames() ()
#11 0x00000000004382a3 in main ()

Sude- commented Jan 19, 2017

Hopefully it won’t crash with this patch.
It should output game name and some json when std::invalid_argument exception is thrown. I’m interested in what it outputs.

hollunder commented Jan 19, 2017 •

Well, it no longer crashes. I don’t think you need the entire list of games, so here is the beginning:

Worth mentioning is that I have the the_witcher_3_wild_hunt dlc, but not the basegame.

Sude- commented Jan 19, 2017

Apparently the crash was caused by null value for updates in json. The value was probably null because of not owning the base game.
22f47de adds a check for this and should fix the issue

hollunder commented Jan 19, 2017

Thanks, it works now.
I wonder what changed, because I had that DLC for a long time.

felisucoibi commented Aug 30, 2018

having this problem with ubuntu 18.04 ppa v 3.3

Sude- commented Sep 5, 2018

@felisucoibi does this happen with latest git version?
If this happens with current git version then I need a backtrace from debug build

Build a debug build

Debugging a simple function

So our professor gave us the task to debug this code. We can use the compiler and also try to use the gdb debugger.

I also used the Debugger a put a breakpoint to lines 19, 20 and 21:

So, I guess the error lies somewhere between lines 19 and 21, but I really can’t figure out what the error is. Hope you guys can help me out.

Terminate called after throwing an instance of std invalid argument what stoi. Смотреть фото Terminate called after throwing an instance of std invalid argument what stoi. Смотреть картинку Terminate called after throwing an instance of std invalid argument what stoi. Картинка про Terminate called after throwing an instance of std invalid argument what stoi. Фото Terminate called after throwing an instance of std invalid argument what stoi

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

The function that throw s an exception is std::stoi that is used to interpret a signed integer value in a string.

you’re trying to convert argv[0] (the program name) into an integer. If your program name isn’t a number, you’re out of luck.

Start the loop at 1 to only try to convert the program arguments to integers.

Terminate called after throwing an instance of std invalid argument what stoi. Смотреть фото Terminate called after throwing an instance of std invalid argument what stoi. Смотреть картинку Terminate called after throwing an instance of std invalid argument what stoi. Картинка про Terminate called after throwing an instance of std invalid argument what stoi. Фото Terminate called after throwing an instance of std invalid argument what stoi

In your reversed function, there is a serious problem in the following line:

So, that for loop will never end (unless the attempt to access v[i] when i equals SIZE_MAX causes the program to crash).

A good compiler, with all warnings enabled, should tell you about this. Clang-cl (in Visual Studio 2019) gives:

warning : result of comparison of unsigned expression >= 0 is always true [-Wtautological-unsigned-zero-compare]

And Visual Studio’s native MSVC compiler gives:

warning C4296: ‘>=’: expression is always true

Gerbera in Gentoo, error: terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi Aborted #994

Comments

cafaia commented Oct 1, 2020

I thank you for your help!

The text was updated successfully, but these errors were encountered:

KarlStraussberger commented Oct 1, 2020

Thanks for reporting and helping to make gerbera even better.

cafaia commented Oct 1, 2020

Hello, thank you for your help!

Here I have the output with gdb:

Thread 20 «gerbera» received signal SIGABRT, Aborted.
[Switching to Thread 0x7fffdcff9700 (LWP 28545)]
0x00007ffff6d87461 in raise () from /lib64/libc.so.6
(gdb)

cafaia commented Oct 1, 2020

Here I have the output with ‘—debug’:

KarlStraussberger commented Oct 1, 2020

Hello, thank you for your help!

Here I have the output with gdb:

Thread 20 «gerbera» received signal SIGABRT, Aborted.
[Switching to Thread 0x7fffdcff9700 (LWP 28545)]
0x00007ffff6d87461 in raise () from /lib64/libc.so.6
(gdb)

Can you type bt before quitting. It gives the stacktrace of the crash.

cafaia commented Oct 1, 2020

Sorry for my lapse, here’s the output of the bt command:

[Switching to Thread 0x7fffdcff9700 (LWP 25985)]
0x00007ffff6d87421 in raise () from /lib64/libc.so.6
(gdb) bt
#0 0x00007ffff6d87421 in raise () at /lib64/libc.so.6
#1 0x00007ffff6d7153b in abort () at /lib64/libc.so.6
#2 0x00007ffff6fa9745 in () at /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/libstdc++.so.6
#3 0x00007ffff6fd95d6 in () at /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/libstdc++.so.6
#4 0x00007ffff6fd9641 in () at /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/libstdc++.so.6
#5 0x00007ffff6fd9893 in () at /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/libstdc++.so.6
#6 0x00007ffff6fac1b8 in std::__throw_invalid_argument(char const*) () at /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/libstdc++.so.6
#7 0x00005555556e418b in ()
#8 0x00005555556e42f8 in ()
#9 0x0000555555660359 in ()
#10 0x00005555556466d3 in ()
#11 0x0000555555649025 in ()
#12 0x000055555564d467 in ()
#13 0x000055555564d827 in ()
#14 0x000055555564fb87 in ()
#15 0x00005555556504d6 in ()
#16 0x0000555555643a34 in ()
#17 0x0000555555644099 in ()
#18 0x00007ffff7e9de67 in start_thread () at /lib64/libpthread.so.0
#19 0x00007ffff6e476cf in clone () at /lib64/libc.so.6
(gdb)

KarlStraussberger commented Oct 2, 2020

Well the gdb output is of no real help, because gerbera was compiled without debug symbols (or stripped afterwards).

whyman commented Oct 2, 2020

You will want to enable symbols for this package, see: https://blog.ramses-pyramidenbau.de/?p=252

cafaia commented Oct 2, 2020 •

Thank you both for your patience and tips!
Now I did the commands again, and that came out:

whyman commented Oct 2, 2020

What is the value of the date in that file?

cafaia commented Oct 2, 2020

The dates in this file are:

I used the date format: day / month / Year

Thanks for your attention and help!

cafaia commented Oct 2, 2020

Problem solved, I removed the folder with the file above and the program returned to work normally.
I have in my collection 258473 audio files and it looks like this is the only one with a problem, is this possible?
With best regards,

Eduardo Coutinho Scalabrin

whyman commented Oct 2, 2020

Yes, it is possible.

To clarify my previous request, I believe it is the metadata date field within the file e.g. ID3 or Vorbis comment etc.

KarlStraussberger commented Oct 2, 2020 •

We should add std::isdigit in that code to avoid future crashes.

cafaia commented Oct 3, 2020

I am sending the file that presented a problem, maybe that helps.
11-Assim Não é Legal.tar.gz

KarlStraussberger commented Oct 3, 2020 •

The file is definitively strange

The fix above did the trick.

Change album, artist and date and you should be able to import it until we can publish an update.

cafaia commented Oct 3, 2020

I did what you said, I changed the tags and put the folder back on the server and everything worked fine!
Thank you so much for everything, whyman and KarlStraussberger, and congratulations on the work!
With best regards,

Ошибка в С++, как решить?

Failed test #5 of 21. Runtime error

Error:
terminate called after throwing an instance of ‘std::invalid_argument’
what(): stoi
Aborted (core dumped)
Terminate called after throwing an instance of std invalid argument what stoi. Смотреть фото Terminate called after throwing an instance of std invalid argument what stoi. Смотреть картинку Terminate called after throwing an instance of std invalid argument what stoi. Картинка про Terminate called after throwing an instance of std invalid argument what stoi. Фото Terminate called after throwing an instance of std invalid argument what stoi

Как я понимаю, Вы уже дошли до парсинга IP-адреса.

✓ Понимаю, что Вы могли видеть решение на Pastebin, но я давно осознал, что сам решил эту задачу неоптимально. Поэтому, извините, если Вы уже ознакомились с моим решением.

Решать следует в таком порядке:

1. Предварительная подготовка. Используйте манипулятор ws перед тем, как ввести строку. Можно даже совместить с вызовом функции getline.

getline (cin >> ws, s);

2. Непосредственно ввод строки, но это указано выше: тот самый вызов getline.

3. Проверка длины строки: если длина меньше 7 или больше 15, то строка НЕ является IP-адресом. Не пропускайте этот пункт!

4. Конкатенация введённой строки с точкой: Вы и сами догадались это сделать, только не нужно добавлять точку в начале строки. Добавить точку в конец строки проще с помощью операции “ + ”.

5. Цикл из 4 итераций, здесь смотрите внимательно!

5.1. Проверяете первый символ — он должен быть цифрой, если нет, то строка НЕ является IP-адресом.
5.2. Только на этом этапе Вы можете использовать функцию stoi; обязательно добавьте ещё один параметр — целочисленную переменную, в ней будет позиция в строке, где встретился символ-разделитель. ✓ Если Вы выполнили пункт 5.1., то в пункте 5.2. ошибок не возникнет!
5.3. Сразу можете проверить распознанное число и символ-разделитель: число должно быть в пределах [0; 255], а разделителем должна быть точка. Если это не так, то НЕ IP-адрес!
5.4. Уделяете подстроку от начала до точки и саму точку. Возврат к пункту 5.1. Важно, чтобы первый символ после точки был цифрой!

6. Проверка конца строки: здесь Вы уже вышли из цикла, но закончилась ли строка? Если в строке не осталось больше символов (проверяется с помощью s.empty()), то радуйтесь — строка ЯВЛЯЕТСЯ IP-адресом! Иначе, строка НЕ является IP-адресом. Конец.

В начале тела цикла необходимо проверять, не кончилась ли строка? Если строка закончится до выхода из цикла, то отвечаем: это не IP-адрес!

✓ Без такой проверки возможен выход за пределы строки.

Минимальный IP-адрес это 4 цифры разделённые тремя точками, отсюда минимальная длина равна 7.

Максимальный IP-адрес это 4 раза по 3 цифры с разделением тремя точками, отсюда максииальная длина равна 15.

А что касается 5 теста, то это выявление реакции на неправильную строку. Первый символ строки не является цифрой. Функция stoi пытается извлекать из строки цифры, но сразу обнаруживает разделитель, поэтому принимает пустую строку. А пустая строка никак не может быть числом. Вследствие этого функция stoi выбрасывает исключение.

Можно решать эту проблему по-разному: или исключить возникновение ошибки, или перехватить исключение и обработать.

а) Проверка первого символа строки позволяет избежать ошибки.

б) Перехват исключения реализуется с помощью блоков try<> и catch()<>

Выполнение этого задания требует от программиста сосредоточенности и пунктуальности как у робота. Важно не упускать даже мелкие детали.

Как видите, я сам не робот — один нюанс я всё-таки упустил (см. выше).

Comments

Malvineous commented Sep 29, 2015

Sorry about spamming you with issues 🙂

If you take docs/sample/sample1.cpp and change this line:

Then when you run the code, you get an unhandled exception error:

The exception looks like it’s got something to do with calculating the sheet index from the filename:

It looks like the input file, produced by MS Excel, has a filename in a format that xlnt isn’t expecting?

The text was updated successfully, but these errors were encountered:

tfussell commented Sep 29, 2015

It’s nice to have someone using something I wrote. I figured there’d be some problems like this showing up eventually.

Your analysis is correct. This code is trying to turn a relationship like «worksheets/sheet1.xml» into «1» and «worksheets/sheet2.xml» into «2». As you can see, it’s not very flexible code. I’ll try to come up with a better method soon.

tfussell commented Oct 2, 2015

My latest commit, 8dc7342, should fix this problem. I’ve made the aforementioned code more robust (I hope). Please give it a try if you get a chance.

Malvineous commented Oct 6, 2015

Almost! Sorry for the delay in testing this, many thanks for the update. Unfortunately it doesn’t completely fix the problem, rather it moves it into workbook.cpp instead. Looks like there’s a similar bit of code there too:

Hopefully it’s just a copy-and-paste to fix that too?

tfussell commented Oct 6, 2015

Copying and pasting this code is not very elegant and means I probably did something incorrect. All the same, it seems to be working now at least to the extent that I can test it.

Malvineous commented Oct 6, 2015

tfussell commented Oct 6, 2015

I tried loading it and saving it. I didn’t have any problems, and the resulting copy appears identical (comparing in Google Docs since I don’t have Office right now).

tfussell commented Oct 6, 2015

It looks like the copy actually has two of each original worksheet and red font color is lost. I’ll create issues for both of these.

Malvineous commented Oct 6, 2015

That’s weird, I still get a segfault when it tries to save the workbook again.

tfussell commented Oct 6, 2015

Did you merge in the most recent commit, 690322? Sorry it’s so complicated to get started. We’ll get it working soon.

Malvineous commented Oct 7, 2015

Oh my apologies! When you said that copying and pasting is not very elegant, I thought you weren’t going to do that as a fix! I didn’t realise you had already done it 🙂 Yes, now I update from the latest git version I no longer get a crash. Sorry about the confusion!

Thanks again for all your help! I really appreciate it.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *