Valgrind无效写入大小8

时间:2012-02-04 20:28:42

标签: c memory valgrind

我正在尝试使用C结构,我已经提出invalid write of size 8后跟来自valgrind的invalid read of size 8消息。

我的代码只循环遍历参数(如果是argc > 1),对于每个文件名,它会扫描stringunsigned int,表示名称和年龄(struct player)。

这是我到目前为止所有的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct player {
  char name[20];
  unsigned int age;
};

struct player *player_new_from_stream(FILE * stream){
  struct player *new_player = (struct player*) malloc(sizeof(struct player));
  char *p_name = malloc(20);
  char *p_age = malloc(20);

  if (stream != stdin){
    if (fgets(p_name, 20, stream) != NULL){
      char *p = strrchr(p_name, '\n');
      if (p)
        *p = '\0';
      strcpy(new_player->name, p_name);
    }
    if (fgets(p_age, 20, stream) != NULL)
      new_player->age = atoi(p_age);
  }
  else {
    printf("enter name and age for a player\n");
    gets(p_name);
    gets(p_age);
    strcpy(new_player->name, p_name);
    new_player->age = atoi(p_age);
  }

  free(p_name);
  free(p_age);
  return new_player;
}

void player_inspect(struct player plyr, char* prefix){
  printf("[%s] name: %s\n", prefix, plyr.name);
  printf("[%s] age : %d\n", prefix, plyr.age);
}

int main(int argc, char* argv[]){
  FILE * stream;
  char* argument;
  // below: trying to allocate (argc - 1) pointers
  // valgrind's --show-origins=yes points here for both errors
  struct player **players = malloc(sizeof(int) * (argc - 1)); 
  int i = 1;
  for (; i < argc; i++){
    argument = argv[i];
    if (strcmp("-", argument) != 0){
      if ((stream = fopen(argument, "r")) == NULL) perror("Error opening file");
      else {
        // the next line emits Invalid write of size 8 in valgrind
        players[i-1] = player_new_from_stream(stream);
        fclose(stream);
      }
    } else {
      players[i-1] = player_new_from_stream(stdin);
    }
  }

  i = 0;
  char buffer[15];
  for (; i < argc - 1; i++){
    sprintf(buffer, "%d", i);
    // the next line emits Invalid read of size 8
    player_inspect(*(players[i]), buffer);
    free(players[i]);
  }

  free(players);
  return 0;
}

这里有什么问题?我想从struct player返回指向player_new_from_stream的指针,并将此指针打包到players中的数组main()

3 个答案:

答案 0 :(得分:4)

这是错误的:

struct player **players = malloc(sizeof(int) * (argc - 1));

请改用:

struct player **players = malloc(sizeof(*players) * (argc - 1));

请注意,在您的系统上sizeof(int) == 4 sizeof(struct player *) == 8

答案 1 :(得分:1)

如果要使用数组,则需要进行双重分配:

struct player **players = malloc(sizeof(struct player*) * (argc - 1));
for (int i=0; i<argc-1;i++)
   player[i] = malloc(sizeof(struct player));

答案 2 :(得分:1)

我在valgrind下使用有效的输入文件(播放器文件)运行它,使用gcc -g编译它并没有给出任何这些无效的读/写消息。

它也适用于使用标准输入。

但是,当我使用不存在的文件运行它时,它在

处有一个读取错误
  i = 0;
  char buffer[15];
  for (; i < argc - 1; i++){
    sprintf(buffer, "%d", i);
    player_inspect(*(players[i]), buffer); // <<HERE
    free(players[i]);
  }

由于如果fopen调用失败,由于该数组索引处的指针未被设置,因此player [i]指针为NULL。