Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

c - strlen result changes with and without a prior printf

I'm starting to build a C function that breaks an HTTP request string apart on " ".

The function creates short local buffers for each row of the HTTP request, where each row is the sub string between char *front and the location of the next delimiter.

However, I'm seeing that the call to strlen() on line 150 reports two different lengths for the request-header depending on whether or not the printf() calls on lines 146 and 147 are present.

When they are included, 150 strlen(header) returns 21 (where header = "Host: www.example.com") Without the printf() statements, 150 strlen(header) returns 30, so the printf() on line 152 includes garbage at the end (Host: www.example.com HT*?U)

struct http_request *string_to_request(char *req, size_t req_len) {
  char *front = req;
  const char *delim = "
";
  size_t delim_len = strlen(delim);

  char *c = strstr(front, delim);

  if (c > front) {
    size_t request_line_len = c - front;
    char request_line[request_line_len];
    strncpy(request_line, front, request_line_len);

    printf("%s
", request_line);
    front += strlen(request_line) + delim_len;

    c += delim_len;
  }

  c = strstr(front, delim);
  size_t header_line_len = c - front;
  char header[header_line_len];
  strncpy(header, front, header_line_len);

  printf("%s
", header);

  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You used strncpy to construct a non null-terminated string. Trying to pass it to printf would only work if you used a string length argument, and strlen won't work at all. The string is exactly c - front characters long, so as far as that goes, you can replace the strlen call with c - front.

So I'm pretty sure you're intending to do something else where that printf call is. You have two design choices to make.

  1. You can abandon null-terminated strings and use counted strings for whatever you intend to call here.

  2. You can allocate one more byte on that array and initialize it to zero and pass it to normal string functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...