且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用char缓冲区处理

更新时间:2023-11-09 22:20:40


  1. 如果你想用你的code重新entrantly远离静态缓存远。


  2. 使用的snprintf()而不是sprintf的(),这样你可以控制的缓冲区溢出。


  3. 您永远不知道多少堆栈空间留在你打电话的情况下 - 所以没有大小在技术上是'安全'。你有很多的余量大部分的时间玩。但是,这一次将让你很好。我用一个经验法则来从来没有把数组在堆栈中。


  4. 在客户端拥有缓冲区,它和它的大小传递给你的函数。这使得它重新进入,不留模糊,至于谁需要管理缓冲区的生命。


  5. 如果你处理字符串数据,请仔细检查字符串函数,以确保它们特别是终止时,他们击中了缓冲区的末尾。 C库是非常不一致的,当涉及到处理在各种功能串终止。


As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:

char buffer[512];
sprintf(buffer, "Hello %s!", userName.c_str());

Or in Windows:

TCHAR buffer[MAX_PATH+1]; // edit: +1 added
::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &buffer[0]);

The above sample is how I usually create local buffers (a local stack-allocated char array). However, there are many possible variations and so I'm very interested in your answers to the following questions:

  • Is passing the buffer as &buffer[0] better programming style than passing buffer? (I prefer &buffer[0].)
  • Is there a maximum size that is considered safe for stack allocated buffers?
    • Update: I mean, for example, the highest value that can be considered safe for cross-platform desktop applications on Mac, Windows, Linux desktops (not mobile!).
  • Is a static buffer (static char buffer[N];) faster? Are there any other arguments for or against it?
  • When using static buffers you can use return type const char *. Is this (generally) a good or a bad idea? (I do realize that the caller will need to make his own copy to avoid that the next call would change the previous return value.)
  • What about using static char * buffer = new char[N]; , never deleting the buffer and reusing it on each call.
  • I understand that heap allocation should be used when (1) dealing with large buffers or (2) maximum buffer size is unknown at compile time. Are there any other factors that play in the stack/heap allocation decision?
  • Should you prefer the sprintf_s, memcpy_s, ... variants? (Visual Studio has been trying to convince me of this for a long time, but I want a second opinion :p )

  1. Stay away from static buffers if you ever want to use your code re-entrantly.

  2. use snprintf() instead of sprintf() so you can control buffer overruns.

  3. You never know how much stack space is left in the context of your call -- so no size is technically 'safe'. You have a lot of headroom to play with most of the time. But that one time will get you good. I use a rule of thumb to never put arrays on the stack.

  4. Have the client own the buffer and pass it and its size to your function. That makes it re-entrant and leaves no ambiguity as to who needs to manage the life of the buffer.

  5. If you're dealing with string data, double check your string functions to make sure they terminate especially when they hit the end of the buffer. The C library is very inconsistent when it comes to handling string termination across the various functions.