2

I fall into a interesting problem. When I first call string_to_int, stack created a memory buffer for size 6, and converted to a correct integer. But at the second call, IMO, stack reused the buffer (because smaller than size 6?), i still see content " 513" at the break point, so atoi converted to 56513 instant of 56.

How should I do array to int properly and fast ? I can't use strtoi, or stoi because the array can be sometimes fill by space only. i can't directly pass the array to atoi because the array (char stream from network), for example, can be "123456" but it actually contain 2 separate values "123" and "456"

    static int string_to_int(const char* number, int size)
    {
        char stackbuf[size];
        memcpy(stackbuf, number, size);
        return atoi(stackbuf);
    }

char* ptr1 = "   513"

string_to_int(ptr1, 6); //result = 513

char* ptr2 = "056"

string_to_int(ptr2, 3); //result = 56513
1
  • 1
    Since you're using C++, why not just use stringstream? That way you avoid manual memory management and legacy C APIs. Commented Oct 9, 2015 at 4:13

2 Answers 2

3

You need the nul terminator for atoi to work correctly, try strcpy() instead of memcpy() or copy size + 1 bytes.

Sign up to request clarification or add additional context in comments.

2 Comments

strncpy is a good option as it will also prevent from buffer overflow
@vishal strncpy() has its chance of mis-use too as it does not insure the the string end with '\0'. Exactly the same problem OP is having here.
2

As noted by iharob, the issue is that in your 2nd case, you don't have a null-terminated string for atoi to work with.

static int string_to_int(const char* number, int size)
    {
        char stackbuf[size+1];
        memcpy(stackbuf, number, size);
        stackbuf[size] = '\0'; //or you could use strncpy
        return atoi(stackbuf);
    }

3 Comments

Sorry about that (or if you prefer <voice=SeanConnery>Something something, in the latin alphabet, Jehovah starts with an i</voice>)
He didnt have the terminating zero for the first case neither (there are 3 leading spaces). The zero was there out of luck
Using strncpy() in this context provides no benefit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.