我有一段代码,我运行了几次:
void svnViewStatus()
{
FILE *file;
int i, j, k, q=0, ok;
char mystring[100000], *vect[100000], *var, last[12], first[12];
file = fopen("db_svnViewStatus.txt", "r");
if(file == NULL)
{
printf("error");
}
else
{
i=1;
while(fgets(mystring, 100000, file))
{
if( i > 1)
{
j=1;
var = strtok(mystring, ";");
while(var != NULL)
{
if(j==3)
{
if(i == 2)
{
strcpy(first, var);
}
strcpy(last, var);
}
if(j == 2)
{
if(q != 0)
{
ok=1;
for(k=0; k<q; k=k+2)
{
if(strcmp(vect[k], var) == 0)
{
*vect[k+1]++;
ok=0;
}
}
if(ok == 1)
{
vect[q] = malloc(strlen(var)+1);
strcpy(vect[q], var);
vect[q+1] = malloc(sizeof(int));
*vect[q+1] = 1;
q = q+2;
}
}
else
{
vect[q] = malloc(strlen(var)+1);
strcpy(vect[q], var);
vect[q+1] = malloc(sizeof(int));
*vect[q+1] = 1;
q = q+2;
}
}
j++;
var = strtok(NULL, ";");
}
}
i++;
}
}
fclose(file);
printf("nr: %d \n", i-2);
printf("first: %s \n", first);
printf("last: %s \n", last);
for(i=0; i<q; i = i+2)
{
printf("User %s: %d \n", *vect[i], *vect[i+1]);
}
for(i=0; i<q; i=i+1)
{
free(vect[i]);
}
}
在db_svnViewStatus.db中我有:
NumeRepo:CitateWoodyAllen;DataCreat:12 Nov 2011;Detinator:Ioana;Descriere:Citate ale faimosului regizor Woody Allen
1;Ioana;12 Nov 2011;Woody Allen;What if everything is an illusion and nothing exists? In that case, I definitely overpaid for my carpet.
2;Mihai;12 Nov 2011;Woody Allen;The lion and the calf shall lie down together but the calf won't get much sleep
3;Mihai;13 Nov 2011;Woody Allen;Eighty percent of success is showing up
4;Cristi;23 Nov 2011;Woody Allen;It is impossible to travel faster than the speed of light, and certainly not desirable, as one's hat keeps blowing off
5;Ioana;25 Nov 2011;Woody Allen;I had a terrible education. I attended a school for emotionally disturbed teachers.
6;Cristi;25 Nov 2011;Woody Allen;I will not eat oysters. I want my food dead. Not sick. Not wounded. Dead.
但是我得到了这个:
"检测到堆损坏:在0x000032E90处的普通块(#54)之后。 CRT检测到应用程序在堆缓冲区结束后写入内存。"
需要帮助吗?
此外,我在分配内存后应该使用free吗?为什么?
vect[q]
和vect[q+1]
,但你释放了vect[0]
到vect[q-1]
。你是否分配了你要释放的资源,并释放了你所分配的资源? - Jonathan Lefflerxx.c:43: warning: value computed is not used / xx.c:78: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
? 如果有,那就修复它们。如果没有,请将编译器警告级别提高 - 或者使用一个会抱怨的编译器。你学过struct
吗?如果是,请使用它。如果没有,那么你所做的事情只有微不足道的借口。(GCC 4.2.1 / LLVM 在 MacOS X 10.7.2 上使用-Wall -Wextra
产生了上述警告。) - Jonathan Lefflerif (strcmp(vect[k], var) == 0) { (*vect[k+1])++; ok = 0; }
。至少GCC会警告您有麻烦。您使用了*vect[k+1]++;
,这会增加指针而不是指向的整数。然后一切都失控了。请注意您的编译器-并确保您提高警告级别,以便获得所需的帮助。 - Jonathan Leffler%s
和int
问题在printf()
接近结尾处;您传递的是*vect[i]
,它是一个字符(升级为int
,因此出现警告),而不是vect[i]
。使用结构体可以节省空间和烦恼。您有一个char *
数组,其中将偶数索引视为字符串,奇数索引视为指向int
的指针。最好使用struct data { char *name; int count; }
的数组。 - Jonathan Leffler