简体   繁体   English

堆栈粉碎,找不到溢出错误

[英]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.我正在尝试编写一个函数,如果字符串的长度小于分配给 char 缓冲区的最大大小,它将用一些字符填充字符串。 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.我遇到了“ * 检测到堆栈粉碎 * : ./test 终止”错误,它会停止我的测试程序,因为我假设某处有溢出覆盖了一些受保护的内存。 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谢谢

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. buf_size对于您要执行的操作来说太大了。 Use:用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM