Search code examples
csigabrtstack-smash

C : stack smashing detected but everything is working before return statement


Ok so there are lots of stack smashing detected questions on stackoverflow, I looked at 6-7 of them but couldn't clear my problem.

I have a void function in C named encryptor, which takes a char array, and updates that array.

void encryptor(char* m,char* K){
    char T[5] = "1011\0"; // added the last '\0'
    int l = countOnes(K);
    for (int i=0; i<l; i=i+1){
        char TT[33];
        TT[32] = '\0'; // Last character is '\0'
        strcat(TT,T); strcat(TT,T); strcat(TT,T); strcat(TT,T); strcat(TT,T); strcat(TT,T); strcat(TT,T); strcat(TT,T); // 8 times
        string_xor(m,TT,m);
        addOne(T);
    }
    printf("%s\n", m); // <======*** This print is working
    // The output of print is correct encrypted bitstring 
    // of length 32 : 11011101110111011101110111011101
    return;
}

And here is the the corresponding int main code :

int main(){
    char message[33] = "11001100110011001100110011001100";
    message[32]='\0';
    char key[33] = "00100010001000100010001000100011";
    key[32]='\0';
    // encryptor takes a 32 bitstring and uses key to encrypt it
    // All other functions in encryptor are working and even m is being updated 
    encryptor(message,key);
}

As the flow of program is reaching to the print function just before the return statement and after that stack smashing is detected what could be a possible reason for this

I tried to use gdb debugger but it shows

Program received signal SIGABRT, Aborted. 0x00007ffff7a55860 in raise () from /usr/lib/libc.so.6

Could anyone help me finding out (or any way to find out) the cause of this error (I dont think its because of buffer overflow or something as it reached the print function)

Thanks


Solution

  • Found the big blunder, strcat does not copies the T string to TT but does something via reference.

    And as this pointer is referenced to a something created in function's frame which destroys after end of function it throws an error.

    As character array is basically a pointer, as soon as the function returns that pointers turns garbage values and error comes.