我正在尝试实现一个小散列图表的问题。
map.h
typedef struct Map Map;
Map *map_create();
int map_set(Map *map, char *key, void *val);
map.c
const int MAP_INITIAL_SIZE = 100;
typedef struct MapPair MapPair;
struct MapPair
{
char *key;
void *val;
};
struct Map
{
MapPair **table;
int count;
int limit;
};
Map *map_create(void)
{
Map *map = (Map*)malloc(sizeof(Map));
if (!map) return NULL;
map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));
if (!map->table)
{
free(map);
return NULL;
}
map->count = 0;
map->limit = MAP_INITIAL_SIZE;
return map;
}
void add(MapPair **context, int start, MapPair *pair, int limit)
{
int i = start;
while (context[i] != NULL && strcmp(context[i]->key, pair->key) != 0) // crashing here
{
i++;
if (i == limit) i = 0;
}
context[i] = pair;
}
int map_set(Map *map, char *key, void *val)
{
if (map->count >= map->limit / 2)
{
if (!expand(map)) return 0;
}
MapPair *pair = (MapPair*)malloc(sizeof(MapPair));
if (!pair) return 0;
pair->key = key;
pair->val = val;
add(map->table, hash(key, map->limit), pair, map->limit);
++map->count;
return 1;
}
我最初是使用pelles c进行开发的,但在遇到问题时转移到vs2013调试器。然后在vs2013中,程序会在添加功能时崩溃但不会在pelles c中崩溃。我假设它与我的动态数组有关,我计划以后能够扩展。
有人能告诉我为什么当我尝试访问动态数组的索引时程序似乎崩溃了吗?
答案 0 :(得分:2)
在添加函数中,您正在检查表,直到到达NULL指针:
while (context[i] != N ...
但是当你分配这个表时,你永远不会将这些指针设置为NULL:
map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));
您应该将它们设置为NULL:
for( size_t i = 0 ; i < MAP_INITIAL_SIZE ; i++ )
map->table[i] = NULL ;
否则你将超出该数组的范围。
答案 1 :(得分:1)
我不知道Visual可以编译纯C项目!无论如何,你的崩溃是由一个神奇的字符串引起的:http://en.wikipedia.org/wiki/Magic_number_(programming)
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
(SO来源:In Visual Studio C++, what are the memory allocation representations?)
与GCC(或我想象的像素)不同,Visual Studio将未初始化的堆数组指针设置为0xCDCDCDCD
,而不是NULL
。因此,即使未初始化上下文,您对context[i] != NULL
的检查也会返回true。
......这就是为什么外显总是好于隐含的原因。