【发布时间】:2018-02-04 03:20:12
【问题描述】:
我正在尝试将文本文件保存到线程内的 C 中的字符串中,但我不断收到分段错误。这发生在正在创建的线程的实例中。我以前没有使用过线程,所以我不确定这是否会导致问题。
int getCurrentSegmentWordcount(int segment) { //declaring file pointer (value?)
printf("func\n");
char text[1000];
char buffer[150];
FILE *fp = fopen("words.txt", "r");
if(fp == NULL) {
printf("null file");
}
int i = 0;
// while(feof(fp)) {
// text[i++] = fgetc(fp);
// }
// text[i] = '\0'; //set null char to end string
while(fgets(buffer, 150, fp)) {
strcpy(text[i], buffer);
printf("\n\n %s \n\n", text[i]);
i++;
}
getchar();
pthread_exit(NULL);
}
以下是我的编译器警告。没有错误,但有多个警告。
assign2.c: In function ‘print_hello_world’:
assign2.c:10:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘void *’ [-Wformat=]
printf("Hello World. Greetings from thread %d\n", tid);
^
assign2.c: In function ‘getCurrentSegmentWordcount’:
assign2.c:29:10: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(text[i], buffer);
^
In file included from assign2.c:4:0:
/usr/include/string.h:125:14: note: expected ‘char * restrict’ but argument is of type ‘char’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^
assign2.c:30:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("\n\n %s \n\n", text[i]);
^
assign2.c: In function ‘main’:
assign2.c:46:77: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
status = pthread_create(&threads[i], NULL, getCurrentSegmentWordcount(i), (void * )i);
^
assign2.c:46:46: warning: passing argument 3 of ‘pthread_create’ makes pointer from integer without a cast [-Wint-conversion]
status = pthread_create(&threads[i], NULL, getCurrentSegmentWordcount(i), (void * )i);
^
In file included from assign2.c:1:0:
/usr/include/pthread.h:233:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘int’
extern int pthread_create (pthread_t *__restrict __newthread,
^
assign2.c:52:7: warning: passing argument 1 of ‘exit’ makes integer from pointer without a cast [-Wint-conversion]
exit(NULL);
^
In file included from assign2.c:3:0:
/usr/include/stdlib.h:543:13: note: expected ‘int’ but argument is of type
‘void *’
extern void exit (int __status) __THROW __attribute__ ((__noreturn__));
./assign2exec
Main here. Creating thread 0
func
Makefile:20: recipe for target 'all' failed
make: *** [all] Segmentation fault (core dumped)
【问题讨论】:
-
在这个语句中“strcpy(text[i], buffer);”什么是“文本[i]”...??它需要是什么???另外,“i++”是正确的做法吗..??
-
你的编译器警告告诉你什么?
-
text[i] 是字符串文本中的当前字符。我相信 i++ 是正确的,因为我们必须移动到下一个字符。我的编译器说分段错误
-
检查“strcpy()”上的“man”页面...它的第一个参数的类型是什么?您确实收到了关于它的编译器警告...警告行以“assign2.c:29:10:”开头(顺便说一句,这些提示可以帮助您在没有人告诉您的情况下找到答案。)
标签: c gcc segmentation-fault