段错误~~
发表于 : 2007-09-27 8:59
由于昨天升级不慎,系统崩溃,重新安装之后,相同的程序出现段错误……
#include <stdlib.h>
#include <string.h>
#define M 1000000
#define LEN 100
void transfer(char *in)
{
char * word[M];
int times[M];
float frequency[M];
char * flag = NULL;
//gdb调试到这里出错……
char * source = (char *)malloc(LEN);
char * label = (char *)malloc(LEN);
char * token = (char *)malloc(LEN);
int i = 0;
int j;
int sum = 0;
strcpy(source, strtok(in, " "));
strcpy(label, strtok(NULL, " "));
printf("%s",label);
while(1)
{
flag = strtok(NULL, " ");
if(flag == NULL)
break;
strcpy(token, flag);
word = (char *)malloc(LEN);
strcpy(word, token);
flag = strtok(NULL, " ");
if(flag == NULL)
break;
strcpy(token, flag);
times = atoi(token);
sum += times;
i++;
}
for(j=0;j<i;j++)
{
frequency[j] = times[j]*1.0/sum;
printf(" %s:%f",word[j],frequency[j]);
}
printf("\n");
for(j=0;j<i;j++)
free(word[j]);
free(label);
free(source);
free(token);
}
int main()
{
char * in = (char *)malloc(M);
char * fileName = (char *)malloc(LEN);
freopen("output.txt", "w",stdout);
scanf("%s",fileName);
FILE *fp = fopen(fileName, "r");
while(fgets(in, M-1, fp) != NULL)
{
transfer(in);
}
fclose(fp);
free (in);
free (fileName);
return 0;
}
#include <stdlib.h>
#include <string.h>
#define M 1000000
#define LEN 100
void transfer(char *in)
{
char * word[M];
int times[M];
float frequency[M];
char * flag = NULL;
//gdb调试到这里出错……
char * source = (char *)malloc(LEN);
char * label = (char *)malloc(LEN);
char * token = (char *)malloc(LEN);
int i = 0;
int j;
int sum = 0;
strcpy(source, strtok(in, " "));
strcpy(label, strtok(NULL, " "));
printf("%s",label);
while(1)
{
flag = strtok(NULL, " ");
if(flag == NULL)
break;
strcpy(token, flag);
word = (char *)malloc(LEN);
strcpy(word, token);
flag = strtok(NULL, " ");
if(flag == NULL)
break;
strcpy(token, flag);
times = atoi(token);
sum += times;
i++;
}
for(j=0;j<i;j++)
{
frequency[j] = times[j]*1.0/sum;
printf(" %s:%f",word[j],frequency[j]);
}
printf("\n");
for(j=0;j<i;j++)
free(word[j]);
free(label);
free(source);
free(token);
}
int main()
{
char * in = (char *)malloc(M);
char * fileName = (char *)malloc(LEN);
freopen("output.txt", "w",stdout);
scanf("%s",fileName);
FILE *fp = fopen(fileName, "r");
while(fgets(in, M-1, fp) != NULL)
{
transfer(in);
}
fclose(fp);
free (in);
free (fileName);
return 0;
}