使用 valgrind 时获得 int 变量指针的无效读取大小错误



我在使用 valgrind 时收到以下错误,我无法调试。

  Memcheck, a memory error detector
==9215== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==9215== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==9215== Command: ./memleak 1
==9215== 
==9215== Invalid read of size 4
==9215==    at 0x400CEC: test1(int*, int) (memleak.cpp:11)
==9215==    by 0x400F0F: main (memleak.cpp:55)
==9215==  Address 0x5a1a05c is 0 bytes after a block of size 28 alloc'd
==9215==    at 0x4C2AFE7: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9215==    by 0x400EAD: main (memleak.cpp:51)
==9215== 
Test 1 sum is 475
==9215== 
==9215== HEAP SUMMARY:
==9215==     in use at exit: 0 bytes in 0 blocks
==9215==   total heap usage: 1 allocs, 1 frees, 28 bytes allocated
==9215== 
==9215== All heap blocks were freed -- no leaks are possible
==9215== 
==9215== For counts of detected and suppressed errors, rerun with: -v
==9215== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

我的代码是:

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
// sum an array of numbers
int test1(int *data, int len)
{
  int sum = 0;
  for(int i=0; i <= len; i++){
    sum += data[i];
  }
  return sum;
}
// Allocate a random number array
char* test2_init()
{
  char buf[80];
  cout << "Enter a word: ";
  cin >> buf;
  char* mydat = new char[strlen(buf)+1];
strcpy(mydat, buf);
return mydat;
}
char* test2_reverse(char* word)
{
  int len = strlen(word);
  char* otherword = new char[len+1];
  for(int i=0; (unsigned)i < strlen(word); i++){
    otherword[i] = word[len-i-1];
  }
  otherword[len+1] = '';
  delete [] word;
  return otherword;
}
int main(int argc, char* argv[])
{
  if(argc < 2){
    cerr << "Please enter the test number you want to run [1-2]" << endl;
    return 1;
  }
  const int len = 7;
  int test = atoi(argv[1]);
  if(test == 1){
    // Test should sum up the array values and print it
    int *data = 0;
    data=new int[len];
    for(int i=0; i < len; i++){
      data[i] = rand()%100;
    }
    int sum = test1(data, len); 
    delete [] data;
    cout << "Test 1 sum is " << sum << endl;
  }
  else if(test == 2){
    // Test should create a random string & then reverse a copy
    char* myword = test2_init();
    cout << "myword is " << myword << endl;
    char* otherword = test2_reverse(myword);    
    cout << "otherword is " << otherword << endl;
    delete [] myword;
    delete [] otherword;
  }
  else {
    cout << "Unknown test number" << endl;
  }
  return 0;
}

无法找出大小 4 错误无效读取的原因。我知道我应该使用向量,但我想为这个项目使用 new。

for(int i=0; i <= len; i++)
                ^

访问所有索引,包括len . len本身已经过了数组的末尾,或者正如 Valgrind 所说,"块后的 0 字节"。测试应该是规范i < len

for(int i=0; i <= len; i++){
    sum += data[i];
}

应该是

for(int i=0; i < len; i++){
    sum += data[i];
}

您正在读取数组末尾的末尾。 指数0...len有效,data[len]无效。

最新更新