Char array (returned from a function) is empty unless I print it in the function. Why does the printf() matter in this case?

时间:2018-03-22 23:29:47

标签: c recv

So, I'm learning network programming right now, and I'm running this accept loop:

while (1) {
  int new_fd = accept(sockfd, etc, etc);
  my_struct read_data = read_all(new_fd);

  if (read_data.status < 0) {
    fprintf(stderr, "%s\n", "Failure");
  } else {
    printf("%s\n", read_data.buffer);
  }
}

So everytime a new request comes in, I try to read the data.

Here's the interesting part. This is my read_all() function:

my_struct read_all(int fd) {  
  size_t len = 0;
  recv(fd, &len, sizeof(len), 0);

  char buffer[len];  
  while (bytes_read < bytes_to_read) {
     recv(fd, buffer + bytes_read, bytes_to_read, 0);
  }  
  read_data.buffer = buffer;
  read_data.status = 0;
  return read_data;
}

Obviously, this is only a snippet of the logic, but I think it gets the point across. I first receive the "header" which is simply the size of the real data. Then I initialize a char array buffer with this size. I make sure to populate the buffer. And finally, I assign the char array to my struct and return it.

Now, in the first code block, you'll see that I print the content of this buffer if the status was not a failure.
At this point, the first accept() (or request) will either not print anything or it prints "%%%%%%%%%%". The rest of the requests that come in later on will print just fine with the actual data.

Curiously enough, if I put in a printf("%s\n", read_data.buffer) call in read_all() right before I return read_data, the printing in the first code block works perfectly.

So printing the variable makes it work properly, and I'm unable to figure out why that is. I'm assuming it has something to do with the way I'm initializing the first time around? What am I doing wrong?

0 个答案:

没有答案