[英]Bus error running a program in C
I am trying to compile a program I wrote in C but can't get rid of a 'bus error' when running the program. 我正在尝试编译用C语言编写的程序,但在运行该程序时无法摆脱“总线错误”。 I came across other threads mentioning 'string literals' and memory issues but I think it's time I ask for a fresh look over my code.
我遇到了其他提到“字符串文字”和内存问题的线程,但我认为是时候要求对代码进行全新的外观了。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Counting the words: 数词:
int count(char *str)
{
int i = 0;
int k = 0;
while (str[i])
{
if (str[i] != ' ')
{
while (str[i] != ' ')
i++;
k++;
}
else
i++;
}
return (k);
}
Extracting the words: 提取单词:
void extract(char *src, char **dest, int i, int k)
{
char *tabw;
int j = 0;
while (src[i + j] != ' ')
j++;
tabw = (char*)malloc(sizeof(char) * j + 1);
j = 0;
while (src[i + j] != ' ')
{
tabw[j] = src[i + j];
j++;
}
tabw[j] = '\0';
dest[k] = &tabw[0];
return;
}
Splitting the string into words: 将字符串拆分为单词:
char **split(char *str)
{
int i = 0;
int k = 0;
char **dest;
dest = (char**)malloc(sizeof(*dest) * count(str) + 1);
while (str[i] != '\0')
{
while (str[i] == ' ')
i++;
if (str[i] != ' ')
extract(str, dest, i, k++);
while (str[i] != ' ')
i++;
}
dest[k] = 0;
return (dest);
}
Printing: 印刷:
void ft_putchar(char c)
{
write(1, &c, 1);
}
void print(char **tab)
{
int i = 0;
int j;
while (tab[i])
{
j = 0;
while (tab[i][j])
{
ft_putchar(tab[i][j]);
j++;
}
ft_putchar('\n');
i++;
}
}
int main()
{
print(split(" okay blue over"));
}
Do you guys have any idea? 你们有什么主意吗? Thanks!
谢谢!
while (str[i] != ' ')
in count
goes beyond end-of-string if no space is encountered (eg at end of line). 如果未遇到空格(例如,在行尾
while (str[i] != ' ')
,则count
while (str[i] != ' ')
超出字符串末尾。 I see you make this mistake at multiple places (in both extract
and split
): you assume you will see a space, but that is not necessarily true. 我看到您在多个地方(在
extract
和split
)都犯了这个错误:您假设将看到一个空格,但这不一定是正确的。 For example, the last word of the string you pass in main
is not followed by a space. 例如,您在
main
传递的字符串的最后一个单词后没有空格。
Use: while (str[i] != ' ' && str[i] != 0 )
使用:
while (str[i] != ' ' && str[i] != 0 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.