【问题标题】:How to read an integer from a socket in C如何从 C 中的套接字中读取整数
【发布时间】:2015-03-04 17:31:39
【问题描述】:

我正在尝试从套接字读取 char 数组并获取可以在 for 循环中使用的整数值。可悲的是,我在 atoi() 处遇到了分段错误。我究竟做错了什么?

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);

【问题讨论】:

  • 这取决于它在另一边的写法。顺便说一句,该代码不会编译...
  • 你确定你正在读取的字节是 ASCII 吗?
  • 你有客户端写入socket的代码吗?
  • 在代码中的错误点处放置一个断点。此时查看tmp 中包含的实际值。您可能会发现实际内容与您的预期不符,您可以在代码中进行相应的调整。
  • 我怀疑没有必要创建这个较短的数组”你试过没有它吗?

标签: c arrays sockets char int


【解决方案1】:

确保tmp 是一个C-“字符串”,即带有0 终止符。更改以下内容:

char tmp[bytesRead]; 

成为

char tmp[bytesRead + 1] = "";

上面的修改做了两件事:

  1. 再分配一个字节然后你将使用。
  2. 将所有字节设置为零。

因此,如果您通过调用strncpy() 覆盖第一个stbytesRead 字节,最后一个字节保持不变,并且继续为'\0',即0-终止 char-array 并使其成为 C-“字符串”。


顺便说一句,这一行:

buffer[bytesRead] = '\0';

要求buffer 至少引用1024 + 1 字节...


介绍tmp 的用法并不是必须的。代码也可能如下所示:

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");
  }
  ...
}

【讨论】:

  • 但是当你可以调用atoi(buffer) 时,为什么还要将字符串从buffer 复制到tmp
  • @davmac:不要问我,问 OP ... ;-)
  • requires buffer to refer to at least 1024 + 1 bytes ... 还要求 bytesRead 为非负数,不能保证...
  • @wildplasser:绝对!
  • 谢谢@alk 我想我现在明白了!
猜你喜欢
  • 1970-01-01
  • 2013-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 2015-02-12
  • 2020-10-20
  • 1970-01-01
相关资源
最近更新 更多