[英]Why do I have segmentation fault in this if line?
Recently I was making a program and it was giving me segmentation fault. 最近,我正在编写一个程序,这给了我分割错误。 After using gdb, I realized where I had the problem but I can't solve that.
使用gdb后,我意识到问题出在哪里,但我无法解决。
The function is the following: 该函数如下:
int readSocket_line(int socket, char * array) {
int i = 0;
while (1) {
if (read(socket, & array[i], 1) < 0) {
return -1;
break;
}
if ((array[i] == '\n') || (array[i] == ' ')) {
break;
}
i++;
}
array[i] = '\0';
return 0;
}
The error that is shown by gdb is the following: gdb显示的错误如下:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb3df5b40 (LWP 24457)]
0x08048f70 in readSocket_line (socket=18, array=0xb3df5337 "")
at sockets_clie.c:14
14 if((array[i] == '\n') || (array[i] == ' ')){
I can't understand how can I solve that problem. 我不明白该如何解决这个问题。
I would like some help to solve and understand this error. 我需要一些帮助来解决和理解此错误。 Thank you!
谢谢!
A segmentation fault occurs when a program tries to read/write from an illegal location in memory. 当程序尝试从内存中的非法位置读取/写入时,将发生分段错误。 Your function will keep incrementing the value of i until either a '\\n' (newline) or ' ' (space) is found.
您的函数将一直递增i的值,直到找到'\\ n'(换行符)或''(空格)为止。 If neither of those conditions occur, i will keep incrementing and may cause &array[i] to point to a location in memory that is not writeable.
如果这些条件都没有发生,我将继续递增,并可能导致&array [i]指向内存中不可写的位置。
On another note, the name of your function is a bit misleading as usually line endings are marked with a '\\n' or '\\r' or both. 另一个要注意的是,函数的名称有点误导,因为通常行尾都标有'\\ n'或'\\ r'或两者都有。 A ' ' does not usually mark a line ending.
“”通常不会标记行尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.