简体   繁体   中英

How to read an integer from a socket in C

I am trying to read in the char array from the socket and get the integer value which can then be used in a for loop. Sadly I am getting a segmentation fault at atoi(). What am I doing wrong?

bytesRead = read(sock, buffer, 1024);
buffer[bytesRead] = '\0';
char tmp[bytesRead];                // I suspect creating this shorter 
strncpy(tmp, buffer, bytesRead);    // array is not necessary... but not sure.
int num = atoi(tmp);

To make sure tmp is a C-"string", that is carries the 0 terminator. change the following:

char tmp[bytesRead]; 

to be

char tmp[bytesRead + 1] = "";

The modifications above do two things:

  1. Allocate one more bytes then you will use.
  2. Set all bytes to zero.

So if you overwrite the 1 st bytesRead bytes by the call to strncpy() the last byte stays untouched and with this continues to be '\\0' , that is it 0 -terminates the char -array and with this make it a C-"string".


Btw, this line:

buffer[bytesRead] = '\0';

requires buffer to refer to at least 1024 + 1 bytes ...


Introducing the usage of tmp however isn't necessary. The code also might look like this:

char buffer[1024 + 1];
ssize_t result = read(sock, buffer, sizeof buffer - 1);
if (-1 == result) 
{
  perror("read() failed");
}
else
{
  size_t bytesRead = result;
  buffer[bytesRead] = '\0';
  int num = atoi(buffer);
  if (0 == num)
  {
    fprintf(stderr, "atoi() (might have) failed");
  }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM