Ale*_*lex 2 c string parsing compiler-errors
我遇到了用新行字符拆分字符串的问题.
这个想法是服务器向客户端发送消息,客户端通过其他2个字符串中的换行符分割消息
我收到了分段错误错误.
这是客户端部分,它接收,分割和输出结果.
char response[256];
rc = read(sockfd, &response, 256);
printf("The response is: %s\n", response);//prints the string in 2 lines
char * pch;
pch = strtok (response, "\n");
printf("Part 1 -> %s\n\n", pch); // ERROR
pch = strtok (NULL, "\n");
printf("Part 2 -> %s\n\n", pch);
Run Code Online (Sandbox Code Playgroud)
错误消息显示:
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)
更换
rc = read(sockfd, &response, 256);
Run Code Online (Sandbox Code Playgroud)
同
rc = read(sockfd, response, 256);
Run Code Online (Sandbox Code Playgroud)
response 已经是指向缓冲区的指针.
很可能是(a)response没有初始化,(b)read()函数没有读取字符串中的终止空值.要演示,请使用:
int rc = read(sockfd, response, sizeof(response));
printf("The response is: %.*\n", rc, response);
Run Code Online (Sandbox Code Playgroud)
你应该rc在printf()语句中使用它之前检查它既不是负面的(读取失败)也不是零(EOF),并且在将它传递给strtok()et 之前你需要将null终止,所以可能更好的处理是:
int rc = read(sockfd, response, sizeof(response)-1);
if (rc <= 0)
...error or EOF...
response[rc] = '\0';
Run Code Online (Sandbox Code Playgroud)
我仍然得到错误......
您已在以下位置标记了发生错误的代码:
char *pch;
pch = strtok(response, "\n");
printf("Part 1 -> %s\n\n", pch); // ERROR
Run Code Online (Sandbox Code Playgroud)
核心转储最合理的原因是pch包含空指针.因此,为了保护自己,请测试结果strtok():
char *pch = strtok(response, "\n");
if (pch == 0)
printf("strtok() failed\n");
else
printf("Part 1 -> %s\n\n", pch);
Run Code Online (Sandbox Code Playgroud)
您应该确保if pch为null,您不会继续使用它.
你没有表明声明rc; 如果是unsigned char rc,则255值可能表示从read()调用返回-1 .
另外,我显示代码假定的定义response()是作为阵列可见的(无论是在文件范围或功能范围,而不是作为一个参数的函数).当数组是函数参数时,sizeof(response)返回相同的值sizeof(char *),这通常不是数组的大小.