'I am stuck in this codes in GCC

I was testing the code in GCC in Linux. So far so good, Here is simple SLOC that i tried to achive... After running the code output is:

<1>
<>
<>

But more impressively when i change order of printf lines giving different results... What is wrong with this code and about this situation could you please assit me... Thanks Regards.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *vbStrReverse(char *pBuffer);
int main(){
    printf("<%s>",vbStrReverse("1"));
    printf("<%s>",vbStrReverse("123456"));
    printf("<%s>",vbStrReverse(""));
}

char *vbStrReverse(char *pBuffer){
    int size=strlen(pBuffer);
    char *ptr =(char*) malloc(sizeof(char)*size+1);
    int i;
    int ax;
    do
    {
        ax=*(pBuffer+i);
        if (ax=='\0'){
            *(ptr+i+1)='\0';
            break;
        }
        *(ptr+i)=*(pBuffer+size-i-1);
        i++;
    } while (1);
    return(ptr);
 }


Solution 1:[1]

The function has undefined behavior.

For starters the variable i was not initialized

int i;

It seems you mean

int i = 0;

In this statement

*(ptr+i+1)='\0';

a garbage can be included in the array pointed to by the pointer ptr for example when the source string is empty and the memory beyond the allocated array will be overwritten

The function can be declared and defined the following way

char * vbStrReverse( const char *pBuffer )
{
    size_t size = strlen( pBuffer );
    char *ptr = malloc( size + 1 );

    if ( ptr != NULL )
    {
        ptr += size;
        *ptr = '\0';

        while ( *pBuffer )
        {
            *--ptr = *pBuffer++;
        }
    }

    return ptr;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1