tags:

views:

33

answers:

1

Hi, I was trying to make a program but, when add sprintf to the equation, I get the following error:

Program received signal: "SIGABRT"

My sprintf is written as follows:

int i;
int g;
char b[6];
sprintf(b, "%d", i*g);

If you need to see the whole code here it is (but you probably don't, just in case though):

#include <stdio.h>
#include <stdlib.h>


int main (int argc, const char * argv[]) {
    int i;
    int g;
    char b[6];
    char temp[6];
    char c[6];
    int lol;
    int revlol;
    int assign;
    for (i = 100; i < 1000; i++)
    {
        sprintf(b, "%d", i*g);
        for (g = 100; g < 1000; g++)
        {
            for (lol = 5; lol > -1; lol--)
            {
                for (revlol = 0; revlol < 6; revlol++)
                {
                    temp[lol] = b[revlol];
                }
                if (temp == b)
                {
                    for (assign = 0; assign < 6; assign++)
                    {
                        c[assign] = b[assign];
                    }
                }
            }
        }
    }
    printf("%s", c);
}

But, the problem only happens when I use sprintf. Also note: I am not using itoa because my compiler does not allow it.

Any help would be appreciated!

+2  A: 

In the actual code you assume that buffer b is big enough to print the result for i*g into, but you never initialize g before its first use on this line:

sprintf(b, "%d", i*g);

But even if g was initialized, you are missing that the buffer also has to hold the \0 character, thus it is too small.

Georg Fritzsche
I did not initialize `g` but, even after putting the `sprintf` after the for loop that initializes `g` it still gives the same error.
thyrgle
Oops I wrote the top example wrong.
thyrgle
I thought so. Note the added comment about the size of `b`.
Georg Fritzsche
Yep, and changing b to the size of 7 fixes that problem. Thanks! Still need to wait another 50 secs or so to accept.
thyrgle
This bug is why in programs that I write I always use snprintf. It is safer all around.
Zan Lynx