打印出字符数组时,Valgrind 大小为 8 的无效读取

Valgrind invalid read of size 8 when printing out a character array

我正在尝试打印出一组字符,但是当我尝试打印出这些行时,valgrind 给出了无效的读取消息。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
void printLines (char *ptArray[]);
char line1[] = "black yummy wolfberry";
char line2[] = "Nate is cute";
char line3[] = "hi there friend";
char line4[] = "abcd";

int main(int argc, char *argv[]){
  char **ptArray = calloc(4, sizeof(char *)); // Line 28 when calling calloc
  ptArray[0] = line1;
  ptArray[1] = line2;
  ptArray[2] = line3;
  ptArray[3] = line4;

  printLines(ptArray); // Line 34 when printLines is called

  free(ptArray);
  return 0;
}

void printLines (char *ptArray[]){
  char **a = ptArray;
  while(*a != NULL){   // Line 232 when invalid read occurs
    printf("%s\n", *a);
    a++;
  }
}  

错误信息如下:

==12029== Invalid read of size 8
==12029==    at 0x40110C: printLines (textsort2.c:232)
==12029==    by 0x4008F2: main (textsort2.c:36)
==12029==  Address 0x5204060 is 0 bytes after a block of size 32 alloc'd
==12029==    at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12029==    by 0x400883: main (textsort2.c:28)

有人知道如何解决这个问题吗?感谢您的帮助!

代码遍历 4 个分配的指针以查找 空指针

  while(*a != NULL){   // Line 232 when invalid read occurs
    printf("%s\n", *a);
    a++;
  }

代码应分配第 5 个并分配给它 NULL

  // char **ptArray = calloc(4, sizeof(char *));
  char **ptArray = calloc(5, sizeof *ptArray);
  ptArray[0] = line1;
  ...
  ptArray[3] = line4;
  ptArray[4] = NULL;

备用,传球次数

void printLinesN(char *ptArray[], size_t count){
  for (size_t i = 0; i<count; i++) {
    printf("%s\n", ptArray[i]);
  }
}  

// Call example
// printLines(ptArray);
printLinesN(ptArray, 4);