C valgrind读取无效

时间:2016-04-05 18:22:47

标签: c valgrind

我的C文件程序中读取了大小为1的异常。我从valgrind那里得到以下信息:

==9072== Invalid read of size 1
==9072==    at 0x4C28FB2: __GI_strlen (mc_replace_strmem.c:404)
==9072==    by 0x401FA8: getJsonRecord (in /.autofs/ilab/ilab_users/csd92/Systems_Programming/Indexer/index)
==9072==    by 0x401CF3: jsonWrite (in /.autofs/ilab/ilab_users/csd92/Systems_Programming/Indexer/index)
==9072==    by 0x400BFC: main (index.c:42)
==9072==  Address 0x51d6e80 is 0 bytes inside a block of size 19 free'd
==9072==    at 0x4C27430: free (vg_replace_malloc.c:446)
==9072==    by 0x400F65: file_handler (index.c:110)
==9072==    by 0x400DBB: directory_handle (index.c:82)
==9072==    by 0x400DDC: directory_handle (index.c:84)
==9072==    by 0x400BC3: main (index.c:34)

定义:

#define trailing_record() ("},\n\0")
#define not_trailing_record() ("}\n\0")
#define record_first() ("\t\t{\"")
#define record_second() ("\" :")

这是我的getJsonRecord:

char * getJsonRecord (char * token, char * frequency, int trailing) 
{

  if(token == 0 || frequency == 0)
  {
    return "Token or frequency == 0";
  }

  char * entry = 0;
  entry = calloc((strlen(token) + strlen(frequency) +30),1);

  int tokensize= strlen (token);
  int freqsize = strlen(frequency);

  strcat(entry,record_first());
  strcat(entry,token);
  strcat(entry,record_second());
  strcat(entry,frequency);

  if(trailing == 0)
  {
   strcat(entry,not_trailing_record());
  } 

  else
  {
    strcat(entry,trailing_record());
  }

  free(frequency);
  return entry;

}

这些是失败时传递给getJsonRecord的值:

token Index_Test/3:29:16, frequency 3 trailing 0
token Index_Test/Temp/cable21.txt, frequency 1 trailing 1

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

Ryan Haining是正确的,有时我的令牌已经在一个条件循环中被释放,我从未想过在编写文件之前会调用它。

修复前的条件循环:

if(filepath_index == (filepath_count))
{

    char ** temp = malloc(filepath_count *2 * sizeof(char *));

    int i = 0;
    for (i = 0; i < filepath_count; i ++){
        temp[i] = malloc(strlen(filepaths[i])+1);
        strcpy(temp[i],filepaths[i]);
        free(filepaths[i]);
    }

    free(filepaths);
    filepaths = temp;
    filepath_count = filepath_count * 2;
}

修复后的条件循环: if(filepath_index ==(filepath_count)) {

char ** temp = malloc(filepath_count *2 * sizeof(char *));
int i = 0;

for (i = 0; i < filepath_count; i ++){
    temp[i] = filepaths[i];
}

free(filepaths);
filepaths = temp;
filepath_count = filepath_count * 2;
}
相关问题