无法访问C中动态分配的struct char指针

问题描述 投票:0回答:1

不幸的是,问题看起来对我来说相当复杂。

我有一组结构和函数。请原谅我糟糕的命名。

hashmap.h

#ifndef HASHMAP_H
#define HASHMAP_H

typedef struct HashMapNode HashMapNode;

struct HashMapNode {
  char *key;
  int  value;
  HashMapNode *collision;
};

typedef struct {
  int size;
  HashMapNode **map;
} HashMap;

HashMap *hashmap_new(size_t size);
HashMapNode *hashmap_node_new(HashMapNode *node);

#endif

hashmap.c

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

HashMapNode *hashmap_node_new(HashMapNode *node){
  
  node = malloc(sizeof(HashMapNode));

  node->key       = NULL;
  node->value     = 0;
  node->collision = NULL;

  return node;

};

HashMap *hashmap_new(size_t size){

  HashMap *hash_map = malloc(sizeof(HashMap));

  hash_map->size = size;
  hash_map->map  = malloc(sizeof(HashMapNode*) * size);

  HashMapNode *node;

  for (int i = 0; i < hash_map->size; i++){  
    node = hashmap_node_new(hash_map->map[i]);
    printf("Node pointer: %p, key pointer: %p, collision pointer %p\n", node, node->key, node->collision);
  };

  return hash_map;

};

这是程序工作流程和错误。

main.c

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

int main(){

  HashMap *hash_map = hashmap_new(100);
  
  printf("%p\n", hash_map->map[4]->key);

  return 0;
};

输出:

...
Node pointer: 0x5607cb89b8b0, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b8d0, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b8f0, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b910, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b930, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b950, key pointer: (nil), collision pointer (nil)
Node pointer: 0x5607cb89b970, key pointer: (nil), collision pointer (nil)
Segmentation fault (core dumped)

程序失败于:

(重要的事实是它无法打印索引> 3的指针)

Program received signal SIGSEGV, Segmentation fault.
main () at usage.c:18
18        printf("%p\n", hash_map->map[4]->key);

GDB调试:

(gdb) print hash_map
$11 = (HashMap *) 0x5555555594a0
(gdb) print hash_map->map[0]->key
$12 = 0x7ffff7fa82f0 <main_arena+1648> "\340\202\372\367\377\177"
(gdb) print hash_map->map[1]->key
$13 = 0x7ffff7fa82f0 <main_arena+1648> "\340\202\372\367\377\177"
(gdb) print hash_map->map[2]->key
$14 = 0x0
(gdb) print hash_map->map[3]->key
$15 = 0x0
(gdb) print hash_map->map[4]->key
Cannot access memory at address 0x61590a616963616d

不太确定我在哪里犯了错误..

c memory malloc allocation
1个回答
0
投票

声明

node = hashmap_node_new(hash_map->map[i]):

不会修改

hash_map->map[i]
。您需要重新分配给它:

node = hash_map->map[i] = hashmap_node_new(hash_map->map[i]);
© www.soinside.com 2019 - 2024. All rights reserved.