I'm currently working on a huffman coding program. I have a file named huffencode.c, that is then linked through a header through what works as my main function encodeFile() down below.
The below function makeCodes() is giving me a Seg fault at the line using memcpy
.I'm getting a SIGSEGV when I run gdb, saying that __memcpy_sse2_unaligned
The function makeCodes() is being called in what you can consider the main for this file, encodeFile()
. I'm passing makeCodes() a sorted linked list that is built in another function that is working fine, a char pointer to hold the current code being generated, a symCodes array to hold the codes for each symbol, and the depth of the huffmanTree.
makeCodes() is supposed to work as intended by the huffman cdoing algorithm, if the current node is not a leaf, I transverse left adding a code of 0 and I transverse right adding a code of 1. If the node is a leaf, I have reached a symbol, and my current code for that symbol is complete, I can add that code to its correct position through the nodes symbol.
To have to versions of the code going at the same time so I can transverse the tree all at once, I'm trying to malloc memory for a copy of the current code, and I have the size of the copiedCode set to be 255 * size(char) because a code can only be the length of 255 bits. I then attempt to copy code into copied code, with the possibility of the length being the maximum. My error is somewhere in here.
Any tips are appreciated.
struct HuffmanTreeNode
{
char symbol;
unsigned long freq;
char code[256];
struct HuffmanTreeNode *left, *right;
struct HuffmanTreeNode* next;
};
void makeCodes(
struct HuffmanTreeNode *node, /* Pointer to some tree node */
char *code, /* The *current* code in progress */
char *symCodes[256], /* The array to hold the codes for all the symbols */
int depth) /* How deep in the tree we are (code length) */
{
printf("Test");
char *copiedCode;
int i;
if(isLeaf(node))
{
code[depth] = 2;
for(i = 0; i < depth; i++)
{
symCodes[node->symbol] = code;
}
}
copiedCode = (char *) malloc(255*sizeof(char));
memcpy(copiedCode, code, 255*sizeof(char));
code[depth] = 0;
makeCodes(node->left, code, symCodes, depth+1);
copiedCode[depth] = 1;
makeCodes(node->right, copiedCode, symCodes, depth+1);
free(copiedCode);
}
My main calling this function, the only thing important here are my variables for makeCodes()
and calling the function makeCodes
:
void encodeFile(FILE* in, FILE* out)
{
int top = 0;
int i;
char *code;
char *symCodes[256] = {0};
int depth = 0;
getFileFreq(in, out);
buildSortedList();
printCodes(buildHuffmanTree(globalSortedLL), globalUsedCh, top);
makeCodes(buildHuffmanTree(globalSortedLL), code, symCodes, depth);
/*test stuff
struct HuffmanTreeNode* tree;
tree = newNode('Q', 1);
insert(tree, 'A', 5);
insert(tree, 'b', 12);
insert(tree, 'd', 4);
insert(tree, 'l', 6);
insert(tree, 'e', 2);
insert(tree, 'f', 3);
insert(tree, 'h', 7);
printf("Test tree: ");
printList(tree);
end of test stuff*/
}