Strange behavior

Hello, the following code runs in an environment where there's no OS. And, by now, no memory management.

It does the job well, if I uncomment the print(".") line...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void BasicTerminal::itoa(int numI){
    int pos;
    char str[50];
    
    if(numI == 0){
        str[pos] = 48;
        str[pos+1] = '\0';
        return;
    }
    
    while(numI > 10){
        
        str[pos] = (numI % 10) + 48;
        numI /= 10;
        ++pos;
    }
    
    //print(".");
    
    str[pos] = numI + 48;
    
    
    
    ++pos;
    
    str[pos] = '\0';
    
    invert(str);
    print(util);
    
    return;
}



invert(str) inverts the C string content and redirects it to util(a char pointer to some ready to use memory)

What can possibly cause it to work well when print(".") is uncommented?




There's nothing wrong with invert() or util, as the following code runs well:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void BasicTerminal::itoahex(int numI){
    int pos = 0;
    char str[50];
    
    
    if(numI == 0){
        str[0]='0';
        str[1]='x';
        str[2]='0';
        str[3]='0';
        str[4]='0';
        str[5]='0';
        str[6]='\0';
        print(str);
        return;
    }
    
    while(numI >= 16){
        str[pos] = (((numI % 16)) + 48);
        if(str[pos]>(48+9)) str[pos] = str[pos] + 7;
        numI /= 16;
        ++pos;
    }
    
    str[pos] = numI + 48;
    if(str[pos]>(48+9)) str[pos] = str[pos] + 7;
    ++pos;
    
    str[pos] = 'x';
    ++pos;
    str[pos] = '0';
    ++pos;
    str[pos] = '\0';
    
    
    
    
    invert(str);
    print(util);
    
    return;
    
    
}
Last edited on
The problem is that pos is uninitialized. Adding that call to print() makes the stars align right so that the memory that pos gets allocated to just happens to contain zero.

invert(str) inverts the C string content and redirects it to util

There's probably no need to do that. Just start at the end of str and fill it in going backwards. The print the string starting at whereever you end up.
Thanks! I'll try that.
You're a 100% right!
It worked. Thanks buddy.
Topic archived. No new replies allowed.