我已经创建了一个可以正常工作的程序,但是当我通过带有这些标志的valgrind运行它时:
-g -std=gnu11 -Wall -Wextra -Werror -Wmissing-declarations -Wmissing-prototypes -Werror-implicit-function-declaration -Wreturn-type -Wparentheses -Wunused -Wold-style-definition -Wundef -Wshadow -Wstrict-prototypes -Wswitch-default -Wunreachable-code
我收到错误"无效读取大小1和#34;。每当我尝试将我的char指针数组与一个字符进行比较时就会发生错误。问题在第二个函数中开始发生,所以我已经包含了代码。因此,在我的第二个函数中,与storelinearray[i]
进行比较的所有内容都是无效读取大小1.可能是什么问题?
int main(int argc, char **argv){
char* storelinearray=NULL;
int lines = amountOfLines(argc,argv[1],&storelinearray);
int maxcounter[7] = {0};
countMaxWord(maxcounter, lines, storelinearray);
}
int amountOfLines(int argc, char argv[],char** array_with_info){
FILE* file = NULL;
int countLines = 0;
char singleLine[1024];
int i = 0;
if(argc==2){
file = fopen(argv, "r");
if(file == NULL){
perror("cant open file");
exit(EXIT_FAILURE);
}
while(!feof(file)){
countLines++;
fgets(singleLine,1024,file);
}
char storelinearray[1024*countLines];
rewind(file);
while(!feof(file)){
storelinearray[i] = fgetc(file);
i++;
}
storelinearray[i] = '\0';
*array_with_info = storelinearray;
}
else{
file = stdin;
if(file == NULL){
perror("cant open file");
exit(EXIT_FAILURE);
}
while(!feof(file)){
countLines++;
fgets(singleLine,1024,file);
}
char storelinearray[1024*countLines];
rewind(file);
while(!feof(file)){
storelinearray[i] = fgetc(file);
i++;
}
storelinearray[i] = '\0';
*array_with_info = storelinearray;
}
fclose(file);
return countLines;
}
void countMaxWord(int maxcounter[7], int lines, char* storelinearray){
int zero = 0;
int first = 0;
int second = 0;
int third = 0;
int fourth = 0;
int fifth = 0;
int sixth = 0;
int k = 0;
for(int i = 0; i < 1024*lines;i++)
{
if(storelinearray[i] == '\0')
{
break;
}
if(storelinearray[i] == ':' || storelinearray[i] == '\n' )
{
k++;
if(storelinearray[i] == '\n' && storelinearray[i+1] == '\n'){
k=0;
}
i++;
if(k>6)
{
zero = 0;
first = 0;
second = 0;
third = 0;
fourth = 0;
fifth = 0;
sixth = 0;
k = 0;
}
}
if(storelinearray[i] != '\0')
{
if(k == 0)
{
zero++;
if(maxcounter[0] < zero){
maxcounter[0] = zero;
}
}
if(k == 1)
{
first++;
if(maxcounter[1] < first){
maxcounter[1] = first;
}
}
if(k == 2)
{
second++;
if(maxcounter[2] < second){
maxcounter[2] = second;
}
}
if(k == 3)
{
third++;
if(maxcounter[3] < third){
maxcounter[3] = third;
}
}
if(k == 4)
{
fourth++;
if(maxcounter[4] < fourth){
maxcounter[4] = fourth;
}
}
if(k == 5)
{
fifth++;
if(maxcounter[5] < fifth){
maxcounter[5] = fifth;
}
}
if(k == 6)
{
sixth++;
if(maxcounter[6] < sixth){
maxcounter[6] = sixth;
}
}
}
}
}
答案 0 :(得分:0)
在您的amountOfLines()
中,storelinearray
已在if (argc==2) {}
范围内宣布。因此,一旦amountOfLines()
返回,它就不再有效,尽管您将其地址保存到*array_with_info
,后来的函数访问了无效的内存地址。
要解决此问题,您需要在storelinearray
或malloc()
的堆上分配calloc()
。