C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4#include <time.h> 5#define MAXLEN 100 6#define SUBLEN 3 7 8struct t_node{ 9 char *substring; 10 int count; 11 struct t_node*left; 12 struct t_node*right; 13}; 14 15struct t_node *t_alloc(void){ 16 return (struct t_node *)malloc(sizeof(struct t_node)); 17} 18 19struct t_node *add_tree(struct t_node *p,char *w){ 20 int cond; 21 if(p->substring==NULL){ 22 p=t_alloc(); 23 p->substring=(char*)malloc(SUBLEN+1); 24 strcpy(p->substring,w); 25 p->count=1; 26 p->left=p->right=NULL; 27 } 28 else if((cond=strcmp(w,p->substring))==0){ 29 p->count++; 30 } 31 else if(cond<0){ 32 p->left=add_tree(p->left,w); 33 } 34 else{ 35 p->right=add_tree(p->right,w); 36 } 37 return p; 38} 39 40 41void tree_print(struct t_node *p){ 42 if(p!=NULL){ 43 tree_print(p->left); 44 printf("%s %d\n",p->substring,p->count ); 45 tree_print(p->right); 46 } 47} 48int main(void){ 49 int i,j; 50 char string[MAXLEN]; 51 int length; 52 char sub[SUBLEN+1]; 53 struct t_node *root; 54 55 root=NULL; 56 scanf("%s",string ); 57 length=strlen(string); 58 printf("l=%d",length); 59 if(SUBLEN>length){ 60 return 0; 61 } 62 else{ 63 for(i=0;i<length-SUBLEN+1;i++){ 64 for(j=0;j<SUBLEN;j++){ 65 sub[j]=string[i];i++; 66 } 67 sub[SUBLEN]=0; 68 root=add_tree(root,sub); 69 } 70 } 71 tree_print(root); 72 return 0; 73 74}
標準入力から文字列を読み込み長さSUBLENの部分文字列を列挙しその頻度と共に
標準出力に表示するプログラムを作ったのですがセグメンテーションフォルトを起こしてしまいうまく
動作しません。
なぜこのようなことが起こってしまうのかを教えて頂けると幸いです。
よろしくお願いいたします。
実行結果
asdffsa
Segmentation fault (コアダンプ)
struct t_node *add_tree(struct t_node *p,char *w){ int cond; if(p==NULL){ この行を変更することによって解決 p=t_alloc(); p->substring=(char*)malloc(SUBLEN+1); strcpy(p->substring,w); p->count=1; p->left=p->right=NULL; } else if((cond=strcmp(w,p->substring))==0){ p->count++; } else if(cond<0){ p->left=add_tree(p->left,w); } else{ p->right=add_tree(p->right,w); } return p; }
回答1件
あなたの回答
tips
プレビュー