D
D
Daniil Demidko2016-05-04 13:04:21
C++ / C#
Daniil Demidko, 2016-05-04 13:04:21

Why does this code crash on startup?

I want to easily convert strings to numbers and vice versa without unnecessary bicycles.
To do this, I write wrappers for a standard atof(char*)function from stdlib.h and a non-standard function, the gcc extension, itoa(int, char*, int)from the same stdlib.h
There were no problems with the first function, but I had to rack my brains with the second.
Here is a working C++ example:

#include <iostream>
#include <cstdlib>

int GetInt( const int  &number )
{
    char *result;
    return itoa(number, result, 10);
}

int main()
{
    std::cout << GetInt( 475); // Все прекрасно работает
}

But here's the catch - since the function is non-standard, it simply won't be included if you compile the code with c -c++11 or -c++14 .
Messing with macros is reluctant, and not good, so I just add the Numbers.c file to the project:
// Numbers.c
#include <stdlib.h>

int GetInt(const int number)
{
    char *result;
    return itoa(number, result, 10);
}

Since this is now C code, there should be no problem with including itoa now, and the project can be compiled with -c++14
Edit main.cpp:
#include <iostream>

extern "C" int GetInt(const int);

int main()
{
    std::cout << GetInt( 475); 
    // Компилируется, но при запуске сразу вылетает
}

Why is everything crashing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Bogachev, 2016-05-04
@Daniro_San

I want to easily convert strings to numbers and vice versa without unnecessary bicycles.

So convert, who's stopping you?
#include <iostream>
#include <string>

int main()
{
    std::string number = "123456";

    int value = std::stoi(number);
    std::cout << value; // 123456 (int)

    std::string number2 = std::to_string(value);
    std::cout << number2; // 123456 (string)
}

P
Peter, 2016-05-04
@petermzg

And who will allocate memory for the result?

char *result; // не инициализированна
return itoa(number, result, 10);

For a 32 bit number, at least 33 bytes is recommended. And since you are returning the result from the function, it will not be possible to allocate this memory on the stack and therefore you will have to take care of freeing the allocated memory next.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question