Dave
Dave

Reputation: 13

C - Different array behavior linux/windows?

I have a litle probem with C programming. I have to write a programm for the university and I wrote the whole programm on my windows pc. I tried it afterwards on a linux system and I got different output.

Here is the code:

char *compress(char *input,int lineSize)    
{   
    int n = 0;
    char *compr = (char*)malloc(lineSize * sizeof(char));
    //compr++;

    char c = *input;    

    while(*input != '\0')
    {
        printf("compr: %s\n",compr);
        if(*input != c)
        {
             snprintf(compr,lineSize,"%s%c%d",compr,c,n);

             n = 0;
             c = *input;
             n++;    
        }
        else
        {

            n++;
        }

        input++;

    }

    snprintf(compr,lineSize,"%s%c%d%c",compr,c,n,'\0');
    printf("compr: %s\n",compr);          

    return compr;    
}

this works as it should on my windows pc, but when I run it on linux I get a file writing error + the "compr" array is empty :/

I hope anyone could help me, couldnt find any solution. thanks

Upvotes: 1

Views: 127

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

Compile with warnings:

warning: function returns address of local variable [enabled by default]

Another possible problem:

snprintf(compr,lineSize,"%s%c%d%c",compr,c,n,'\0');

From the sprintf man page:

Some programs imprudently rely on code such as the following

sprintf(buf, "%s some further text", buf);

to append text to buf. However, the standards explicitly note that the results are undefined if source and destination buffers overlap when calling sprintf(), snprintf(), vsprintf(), and vsnprintf(). Depending on the version of gcc(1) used, and the compiler options employed, calls such as the above will not produce the expected results.

Upvotes: 5

Related Questions