Segmentation fault

chc0613042124 2010-03-26 04:30:40
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

#define WORK_SIZE 256

void* thread_func(void *arg);

sem_t bin_sem;
char work_area[WORK_SIZE];

int main()
{
int ret = -1;
pthread_t thread_id;
void* thread_ret = NULL;

ret = sem_init(&bin_sem, 0, 0);
if (ret != 0)
{
perror("semaphore failed \n");
exit(EXIT_FAILURE);
}

ret = pthread_create(&thread_id, NULL, thread_func, NULL);
if (ret != 0)
{
perror("create thread failed\n");
exit(EXIT_FAILURE);
}

printf("input some text:");
while (strncpy("end", work_area, 3) != 0)
{
fgets(work_area, WORK_SIZE, stdin);
sem_post(&bin_sem);
}

printf("\nwaiting for thread to finish...");

ret = pthread_join(thread_id, &thread_ret);
if (ret != 0)
{
perror("thread join failed\n");
exit(EXIT_FAILURE);
}
printf("thread joined\n");

sem_destroy(&bin_sem);

return 0;
}


void* thread_func(void *arg)
{
sem_wait(&bin_sem);
while (strncpy("end", work_area, 3) != 0)
{
printf("you input %d characters\n", strlen(work_area)-1);
sem_wait(&bin_sem);
}
pthread_exit(NULL);
}

这段程序在LINUX下出现Segmentation fault,我想了半天也没想出来,请教各位
...全文
226 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
leaves2211 2010-03-26
  • 打赏
  • 举报
回复
"Segmentation fault"是段错误,内存访问错误,比如没有访问该内存地址的权限,往只读内存写数据,系统内存区地址等,或者访问malloc申请但是已经释放了的内存。
love_rong 2010-03-26
  • 打赏
  • 举报
回复
你往一个只读内存区域("end")写东西。
谭海燕 2010-03-26
  • 打赏
  • 举报
回复


while (strncpy("end", work_area, 3) != 0)



strncpy用错了你。

换成 strncpy(work_area, "end", 3)就好了


你的代码我改了strncpy()之后,跑起来,已经正常了。
wuyu637 2010-03-26
  • 打赏
  • 举报
回复
gdb一步一步看是什么地方segment fault了,
dongjiawei316 2010-03-26
  • 打赏
  • 举报
回复
Segmentation fault表示你引用了无效指针,在出错前,还有别的打印信息吗?
zhonghaoqing 2010-03-26
  • 打赏
  • 举报
回复
段错误常见的错误有两种:

1 指针
2 访问了系统区

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧