我试图从套接字中读取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);
答案 0 :(得分:2)
为了确保tmp
是一个C - "字符串",它带有0
终结符。改变以下内容:
char tmp[bytesRead];
是
char tmp[bytesRead + 1] = "";
上述修改做了两件事:
因此,如果通过调用bytesRead
覆盖1 st strncpy()
字节,则最后一个字节保持不变,并且这仍然是'\0'
,它是0
- 终止char
- 数组,并使其成为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");
}
...
}