请帮帮我。当我运行这个程序时,我无法弄清楚为什么我会得到一个核心转储。在返回任何内容之前,我可以打印all_albums_p
就好了。为什么我会收到core dumped
?
#include "music_server.h"
struct album_ {
int num_tracks;
char **tracks;
int **playlist_hits;
};
typedef struct album_ album;
album *parse_album(FILE *album_file,int *number_of_albums){
int number_of_album,number_of_tracks,number_of_charaters;
int i,j;
char dummy_space;
int *p;
fscanf(album_file,"%d", &number_of_album);
*number_of_albums = number_of_album;
album *all_albums_p = (album *)malloc(sizeof(album)*number_of_album);
for(j=0;j<number_of_album;j++){
fscanf(album_file,"%d", &all_albums_p[j].num_tracks);
all_albums_p[j].tracks = calloc(all_albums_p[j].num_tracks,sizeof(char));
all_albums_p[j].playlist_hits = calloc(all_albums_p[j].num_tracks,sizeof(int));
/*Line 27*/ for(i=0;i<all_albums_p[j].num_tracks;i++){
fscanf(album_file,"%d", &number_of_charaters);
all_albums_p[j].tracks[i] = (char *)calloc(number_of_charaters+1,sizeof(char));
all_albums_p[j].playlist_hits[i] = (int *)malloc(sizeof(int));
all_albums_p[j].playlist_hits[i] = 0;
fscanf(album_file," ",dummy_space);
fscanf(album_file, "%[^\n]s", all_albums_p[j].tracks[i]);
}
}
return all_albums_p;
}
main(int argc, char *argv[]){
int i,j;
int *number_of_albums,*number_of_tracks,a;
a=0;
number_of_albums = &a;
album *all_tracks_ptr;
album_file = fopen(argv[1],"r");
transaction_file = fopen(argv[2],"r");
if((album_file == NULL) || (transaction_file == NULL)){
printf("Either %s or %s could not be open");
}else{
all_tracks_ptr = parse_album(album_file,number_of_albums);
int number_of_tracks[*number_of_albums];
}
}
错误:
Bus Error (core dumped)
(gdb) bt
#0 0xff277c9c in _smalloc () from /lib/libc.so.1
#1 0xff277d10 in malloc () from /lib/libc.so.1
#2 0xff263830 in calloc () from /lib/libc.so.1
#3 0x00010dd8 in parse_album (album_file=0xff3675bc,
number_of_albums=0xffbff894) at functions.c:27
#4 0x00010b80 in main (argc=3, argv=0xffbff90c) at project3.c:19
答案 0 :(得分:6)
您应该在下面分配sizeof(char*)
而不是sizeof(char)
all_albums_p[j].tracks = alloc(all_albums_p[j].num_tracks,sizeof(char*));
答案 1 :(得分:1)
因为它看起来像一条Unix消息(“Bus Error(core dumped)”),我假设你正在使用某种类型的Unix。
因此,在打开调试信息输出并关闭优化的情况下编译程序。如果您使用的是gcc
或gcc兼容的内容,则可能是-g -O0
命令行选项。
然后运行你的程序并让它崩溃。找到核心转储(在本例中我将其称为corefile
),然后键入:
gdb programname corefile
然后,当您收到gdb提示时,键入bt
(对于backtrace
)以查看程序的堆栈帧。这将告诉你程序崩溃的位置,你可以更仔细地检查程序的那一部分。
<强>更新强>
我认为你的问题在这里:
all_albums_p[j].tracks = calloc(all_albums_p[j].num_tracks,sizeof(char));
album.tracks
定义为char**
。但是,您分配给all_albums_p[j].tracks
的内容是num_tracks
char
大小的内存块。您需要为其分配一块足以容纳num_tracks
char *
的内存块。所以你可能需要将行改为:
all_albums_p[j].tracks = (char **) calloc(all_albums_p[j].num_tracks,sizeof(char *));
答案 2 :(得分:0)
使用调试器或valgrind并找出问题所在的行。然后你会知道代码的哪一部分是坏的。