-1

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

tovry
  • 1
  • 2

1 Answers1

0

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);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Just figure that out! I should have paid more attention to strncpy and its argument specs. But thank you for your helpful and speedy response! – tovry Nov 16 '15 at 04:45