设为首页
收藏本站
用户名
Email
自动登录
找回密码
密码
登录
注册
快捷导航
平台
Portal
论坛
BBS
文库
项目
群组
Group
我的博客
Space
搜索
搜索
热搜:
shell
linux
mysql
本版
用户
LinuxSir.cn,穿越时空的Linuxsir!
»
论坛
›
编程开发讨论区 —— LinuxSir.cn
›
Linux 程序设计专题讨论
›
write()出现段错误
1
2
3
/ 3 页
下一页
返回列表
查看:
1414
|
回复:
21
write()出现段错误
[复制链接]
macarthor
macarthor
当前离线
积分
1551
IP卡
狗仔卡
发表于 2005-7-11 13:32:45
|
显示全部楼层
|
阅读模式
int fd;
char *temp;
fd = open("test.txt", O_CREAT | O_WRONLY | O_APPEND);
temp = "\nhehe\n";
write(fd, temp, sizeof(temp));
复制代码
执行到write时出现segmentation fault
应该是'\n'的问题
可是我想向文件中换行
咋整呢?
thx
回复
使用道具
举报
提升卡
置顶卡
沉默卡
喧嚣卡
变色卡
显身卡
弥敦路九号
弥敦路九号
当前离线
积分
1139
IP卡
狗仔卡
发表于 2005-7-11 14:08:14
|
显示全部楼层
sizeof(temp) 得到的是 char * temp 占有内存的大小(32机上是4),而非你想要的字符串长度,用strlen代替sizeof 别忘了#include <string.h>
回复
支持
反对
使用道具
举报
显身卡
macarthor
macarthor
当前离线
积分
1551
IP卡
狗仔卡
楼主
|
发表于 2005-7-11 14:21:19
|
显示全部楼层
if(strlen(temp) != write(test_fd, temp, strlen(temp))){
....;
}
复制代码
此时有warning:comparison between singed and unsigned integer
还是segmentation fault
回复
支持
反对
使用道具
举报
显身卡
kj501
kj501
当前离线
积分
5317
IP卡
狗仔卡
发表于 2005-7-11 15:53:31
|
显示全部楼层
你怎么也不检查一下open的返回值是否有效?
回复
支持
反对
使用道具
举报
显身卡
macarthor
macarthor
当前离线
积分
1551
IP卡
狗仔卡
楼主
|
发表于 2005-7-11 15:58:23
|
显示全部楼层
在真正的代码里边,所有有返回值的地方我都做了检查
这里就是贴出来简写的部分
回复
支持
反对
使用道具
举报
显身卡
macarthor
macarthor
当前离线
积分
1551
IP卡
狗仔卡
楼主
|
发表于 2005-7-11 16:01:45
|
显示全部楼层
问题所在找到了
char *temp;
temp = "we are champion\n";
memset(temp, 0, strlen(temp));
复制代码
就是段错误
而改为下边的就过去了
char temp[100];
temp = "we are champion\n";
memset(temp, 0, strlen(char) * 256);
复制代码
为什么呢?
回复
支持
反对
使用道具
举报
显身卡
kj501
kj501
当前离线
积分
5317
IP卡
狗仔卡
发表于 2005-7-11 16:03:44
|
显示全部楼层
char *temp= "we are champion\n";指向的是常量字符串,不能修改。
回复
支持
反对
使用道具
举报
显身卡
macarthor
macarthor
当前离线
积分
1551
IP卡
狗仔卡
楼主
|
发表于 2005-7-11 16:11:23
|
显示全部楼层
虽然"we are champion\n"是常量,但是它在等号右边啊
而且下边改变的char *temp不是const型的啊
回复
支持
反对
使用道具
举报
显身卡
kj501
kj501
当前离线
积分
5317
IP卡
狗仔卡
发表于 2005-7-11 16:16:59
|
显示全部楼层
问题在于temp事实上指向的是常量。
回复
支持
反对
使用道具
举报
显身卡
wuhu
wuhu
当前离线
积分
362
IP卡
狗仔卡
发表于 2005-7-11 16:36:47
|
显示全部楼层
是你的空间不够他写,所以才出现这样的seg,
回复
支持
反对
使用道具
举报
显身卡
下一页 »
1
2
3
/ 3 页
下一页
返回列表
高级模式
B
Color
Image
Link
Quote
Code
Smilies
您需要登录后才可以回帖
登录
|
注册
本版积分规则
发表回复
回帖后跳转到最后一页
Copyright © 2002-2023
LinuxSir.cn
(http://www.linuxsir.cn/) 版权所有 All Rights Reserved.
Powered by
RedflagLinux!
技术支持:
中科红旗
|
京ICP备19024520号
快速回复
返回顶部
返回列表