sprintf的缓冲区大小 [英] sprintf buffer sizes

查看:355
本文介绍了sprintf的缓冲区大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手程序员,但通常我可以解开我自己的问题。这一次,我解决了这个问题,但它仍然树桩我。一个朋友建议我问这个社区输入。

I'm a novice programmer, but usually I can unravel my own issues. This time I solved the issue, but it still stumps me. A friend suggested I ask this community for input.

我想打印C.数字我有一个函数来做到这一点使用的sprintf。这些数字不应该超过2位数,所以我用一个2字符缓冲区。不知怎的,这是我的逻辑失败,因为这通过修改传递给sprintf的变量之一,但增加缓冲大小解决了问题导致无限循环。

I'm trying to print numbers in C. I have a function to do this using sprintf. The numbers should never be more than 2 digits so I use a 2-character buffer. Somehow this is where my logic fails, because this causes an infinite loop by modifying one of the variables passed to sprintf, but increasing the buffer size solves the issue.

下面是失败的code:

Here's the failing code:

#include <stdio.h>

void printarray(int array[][4]) {
  int y;
  int z;
  char buf[2];
  for (y=0; y<4; y++) {
    for (z=0; z<4; z++) {
      sprintf(buf, "%d", array[y][z]);
      printf("buf is %s, y is %d and z is %d\n",buf,y,z);
    }   
  }
}

int main() {
  int arr[4][4] = {  {1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}  };  

  printarray(arr);

  return 0;
}

尽快为y到达2,它被重置为0,这样无限循环。改变的buf [2]的buf [8]解决了这个问题。

as soon as y gets to 2, it gets reset back to 0, thus infinite loop. changing buf[2] to buf[8] solves the issue.

推荐答案

你忘了NUL终止。在C语言中的 需要终止一个额外的字符串,所以字符BUF [2] 应该是字符BUF [3 ] 10到99之间的数字容纳

You're forgetting the NUL terminator. In C, strings require an extra character for the terminator, so char buf[2] ought to be char buf[3] to accommodate numbers between 10 and 99.

顺便说一句,你的code说明了为什么的sprintf 是危险的,因为它可以写过去的输出缓冲区,并启用的堆栈溢出攻击的。更好的选择是使用的snprintf

Incidentally, your code demonstrates why sprintf is dangerous as it can write past the output buffer and enable stack smashing attacks. A better options is to use snprintf.

这篇关于sprintf的缓冲区大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆