String-handling practices in C [closed]

2019-01-30 20:12发布

I'm starting a new project in plain C (c99) that is going to work primarily with text. Because of external project constraints, this code has to be extremely simple and compact, consisting of a single source-code file without external dependencies or libraries except for libc and similar ubiquitous system libraries.

With that understanding, what are some best-practices, gotchas, tricks, or other techniques that can help make the string handling of the project more robust and secure?

7条回答
Rolldiameter
2楼-- · 2019-01-30 20:47
  • Work with arrays on the stack whenever this is possible and initialize them properly. You don't have to keep track of allocations, sizes and initializations.

    char myCopy[] = { "the interesting string" };
    
  • For medium sized strings C99 has VLA. They are a bit less usable since you can't initialize them. But you still have the first two of the above advantages.

    char myBuffer[n];
    myBuffer[0] = '\0';
    
查看更多
登录 后发表回答