[英]Segmentation fault in c program,use malloc (Linux os)
this c program works in Windows But Getting " Segmentation fault (core dump)" in Linux.这个 c 程序在 Windows 中工作,但在 Linux 中出现“分段错误(核心转储)”。 I gues couse of error pointers or malloc function.I can't return struct array without pointers and malloc.
我猜是错误指针或 malloc 函数的原因。没有指针和 malloc,我无法返回结构数组。
struct team {
char name[12];
int m_count;
int score;
};
struct team *teamName(){
FILE *fp;
fp=fopen("teams.txt", "r");
struct team *items;
items= (struct team *) malloc(sizeof(struct team) * 10);
int i;
for(i=0; i<10; i++)
{
fscanf(fp, "%s\n" , items[i].name);
}
fclose(fp);
return items;
}
int main(void)
{ struct team *items = teamName();
getMatch(items);
}
There several problems in your code :您的代码中有几个问题:
you do not check fopen success你不检查fopen成功
you do not check fscanf success, and if a read name is greater than 11 you write out of the buffer with an undefined behavior您不检查fscanf 是否成功,如果读取名称大于 11,您会以未定义的行为写出缓冲区
why the \\n
in the fscanf format ?为什么fscanf格式的
\\n
?
if you read less that 10 names some entries are not set, with the risk later to have an undefined behavior如果您阅读的名称少于 10 个,则某些条目未设置,以后可能会出现未定义的行为
A proposal taking my remarks into account can be :考虑到我的评论的建议可以是:
#include <stdio.h>
#include <stdlib.h>
struct team {
char name[12];
int m_count;
int score;
};
struct team *teamName(){
FILE *fp = fopen("teams.txt", "r");
if (fp == NULL)
return NULL;
struct team *items = malloc(sizeof(struct team) * 10);
int i;
for (i=0; i<10; i++)
{
if (fscanf(fp, "%11s" , items[i].name) != 1) {
/* empty other names */
do {
items[i].name[0] = 0;
}
while (++i != 10);
break;
}
}
fclose(fp);
return items;
}
int main(void)
{
struct team *items = teamName();
if (items != NULL) {
for (int i = 0; i != 10; ++i) {
if (items[i].name[0] != 0)
puts(items[i].name);
}
}
/* getMatch(items); */
}
Compilation and execution :编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall m.c
pi@raspberrypi:/tmp $ cat teams.txt
aze qsd
loop
bar
pi@raspberrypi:/tmp $ ./a.out
aze
qsd
loop
bar
pi@raspberrypi:/tmp $
Note the fscanf read words, I mean a name must not contain space, else you need to use for instance fgets注意fscanf读取单词,我的意思是名称不能包含空格,否则您需要使用例如fgets
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.