Search code examples
cbuffer-overflowstrncpystack-smash

stack smashing, cant find overflow error


I'm trying to write a function that will pad a string with some character if the length of the string is less than the max size allocated to the char buffer. I'm encountering a "* stack smashing detected *: ./test terminated" error which halts my test program because I'm supposing there's an overflow somewhere overwriting some protected memory. It seems a simple function, but I can't seem to find the cause of the error.

void pad_string2(char* buf, size_t buf_size, char* str, char* pad) {
      strncpy(buf, str, buf_size);
      size_t pad_size = buf_size - strlen(str);
      printf("pad size: %zu\n", pad_size);
      if (pad_size > 0) {
         unsigned int i = 0;
         while(i < (pad_size - 1)) {
            strncpy((buf + strlen(str) + i), pad, buf_size);
            i++;
         }
      }
      buf[buf_size - 1] = '\0';
} 

I thought it might be an off by one problem, but the length of the test string doesn't seem to exceed the size of the buffer.

char buf[16];
printf("sizeof(buf): %zu\n", sizeof(buf));
pad_string2(buf, sizeof(buf), "testing", "A");
printf("strlen(testing): %zu\n", strlen("testing"));
printf("buf: %s\n", buf);

Output
------
sizeof(buf): 16
pad size: 9
strlen(testing): 7
buf: testingAAAAAAAA
*** stack smashing detected ***: ./test terminated
Aborted

Can anyone lend their assistance?

Thanks


Solution

  • The line:

    strncpy((buf + strlen(str) + i), pad, buf_size);
    

    will end up writing over memory that you are not supposed to. buf_size is too large for what you are trying to do. Use:

    strncpy((buf + strlen(str) + i), pad, 1);