0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
gjvatsalya
  • 1,129
  • 13
  • 29
  • 1
    Local variables (like `buffer`) cease to exist as soon as the function returns. – user3386109 Mar 22 '18 at 23:32
  • When `read_all` returns, the lifetime of the local variable `buffer`, since it is not `static`, ends. Since the variable is no longer valid, the pointer that is being returned points to an invalid object, and accessing it results in undefined behavior. – jxh Mar 22 '18 at 23:44
  • @jxh But why does it work the other times in loop? – gjvatsalya Mar 23 '18 at 00:15
  • @gjvatsalya Because undefined behavior means it might do what you expected. However, it might also crash. Or just print some random garbage. It doesn't really matter what it does if the behavior is undefined. – jxh Mar 23 '18 at 00:32
  • @jxh I see, thanks for the info. I just initialized it outside of the function and then passed it in to the function. Don't know why I didn't think until after I took a break. – gjvatsalya Mar 23 '18 at 02:18

0 Answers0