c - 在 C 中运行程序的总线错误
问题描述
我正在尝试编译我用 C 编写的程序,但在运行程序时无法摆脱“总线错误”。我遇到了其他提到“字符串文字”和内存问题的线程,但我认为是时候要求重新审视我的代码了。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
数单词:
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);
}
提取单词:
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;
}
将字符串拆分为单词:
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);
}
印刷:
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"));
}
你们有什么想法吗?谢谢!
解决方案
while (str[i] != ' ')
count
如果没有遇到空格(例如在行尾),in会超出字符串结尾。我看到您在多个地方(在extract
和split
)都犯了这个错误:您假设您会看到一个空格,但这不一定是正确的。例如,您传入的字符串的最后一个单词main
后面没有空格。
利用:while (str[i] != ' ' && str[i] != 0 )
推荐阅读
- django - 由于缓存无法运行 django
- java - 将数据集写入组合的 xls 文件
- python - ElectrumX 服务器 jsonRPC 认证
- validation - Moodle 3.7 - 用户配置文件自定义字段 - 自定义验证
- c++ - 一旦存在 std::underlying_type_t,“枚举类”相对于简单的“枚举”有什么优势?
- php - 如何通过电报BOT上传和下载照片?
- node.js - 将 xml 数据从 nodejs 应用程序发送到 mssql 数据库 SP 时的连接问题
- java - Spring Security 通过 post 对用户进行身份验证
- mysql - 如何选择读过史蒂文·金但没读过威廉·莎士比亚的用户
- javascript - 鼠标点击回调和间隔函数如何同时执行?