C language string concatenation of heap and stack

  • 2020-05-12 02:54:31
  • OfStack

Let's start with 1 demo:


int do_sth(int type) {
  char *errstr;
  
  switch(type) {
  case 1:
    errstr = "Error";break
  case 2:
    errstr = "Warn";break
  case 3:
    errstr = "Info";break
  case 4:
    errstr = "Debug";break
  default:
    return 0;
  }
 
  if (...) {..}
  if (...) {
    ..;
    fprintf(stdout, "%s %s", errstr, ...);
    return 1;
  }
  if (...) { return 1;}
  if (...) {
    fprintf(stderr, "%s %s", errstr, ...);
  }
  ...
  return 0;
}

Question: how do I add an HOSTNAME environment variable before the errstr information?

Given that errstr may write to the standard error, may write to standard output, or may not output at all, it is obviously not appropriate to output HOSTNAME information early

Considering that there are quite a few references to errstr, it is better to splice HOSTNAME to the errstr at the beginning of 1. Then how to splice it?

If you are in a scripting language or a language with gc, you can splicing the dynamically acquired environment variable directly in front of the errstr variable, such as:


errstr=getenv("HOSTNAME") + errstr ;

But you can't do that with c, why not? String concatenation function is not there, such as: strcat;

The truth is not so simple. Why?

The above errstr variable is stored on the stack, so there is no need to consider the problem of free. The original author considers the following 1 complicated if branch. If you put errstr on the stack, you should consider whether you should drop errstr free.

For HOSTNAME, it is a runtime information, so it cannot be put on the stack. If it must be splicing with errstr, errstr must be on the heap, that is, malloc should be dynamic. Therefore, for scripting language, a very simple logic is so troublesome in C

Solutions:

In order to concatenate strings without free, you can define an array of 1 character, such as errstr[255], and then add the required information. To avoid overstepping the bounds with too much information, you can use the snprintf function to automatically discard the overlength section

conclusion


Related articles: