can figure out the problem with my realloc inside the function - c

I'm writing a program that needs to call a function that adds numbers until -1 is introduced, the problem is that after 3 numbers the program stops and gives segmentation fault:
int leNumeros(int **lista, int *nElem, int *tam)
{
int op, *temp = NULL;
*lista = (int*) malloc(*tam * sizeof(int));
if(*lista == NULL)
{
printf("memory fail\n");
} else
{
do
{
printf("number:\n");
scanf("%d",&op);
if(op >= 0)
{
if(*nElem >= *tam)
{
*lista = (int*) realloc( *lista, *nElem * sizeof(int) );
if(*lista == NULL)
{
printf("memory fail");
}
else
{
printf("added: %d bytes total: %d bytes\n",
*nElem * sizeof(int), *nElem * sizeof(int) + *tam * sizeof(int));
//*lista = temp;
}
}
*lista[*nElem] = op;
(*nElem)++;
}
}while(op >= 0);
}
}
int main(int argc, char** argv) {
int *lista = NULL, nElem = 0, tam = 0;
leNumeros(&lista, &nElem, &tam);
return (EXIT_SUCCESS);
}
I'm having trouble understanding what is going on, can anyone help me please?

When leNumeros() is called you attempt to allocate a zero length block - that has implementation defined behaviour.
Then when you enter a number > 0, you attempt to realloc() a zero length block - that behaviour is well defined it frees the original block then returns a null pointer, then at *lista[*nElem] = op; you deference that null pointer rather than aborting the loop.
In any event *lista[*nElem] = op; should be (*lista)[*nElem] = op;
Even if *nElem was non-zero, the line:
*lista = (int*)realloc(*lista, *nElem * sizeof(int));
is bad-practice, because if the reallocation fails the original block will leak because *lista will be come NULL without releasing whatever it previously pointed to. Instead you should (for example):
int* new_block = realloc(*lista, *nElem * sizeof(int));
if( new_block == NULL )
{
printf( "memory fail\n" ) ;
break ;
}
*lista = new_block ;
To work at all in main tam must be > 0, and to avoid possible failure due to implementation defined behaviour nElem should also be grater than zero.

I think the tam parameter is probably the block size to allocate. So for example, if tam = 10, allocate space for 10 ints. Then after taking 10 ints, realloc for 10 more.
Also, note that because of operator precedence, *lista[*nElem] = op; is the same as *(lista[*nElem]) = op;. You want to deference the pointer first, then use the brackets: (*lista)[*nElem] = op;
void leNumeros(int **lista, int *nElem, int *tam)
{
if (*tam <= 0) {
puts("Error: tam must be > 0");
return;
}
int op;
// Keep track of how many ints the array can hold
int items_allocated = *tam;
*lista = malloc(*tam * sizeof(int));
if (*lista == NULL)
{
printf("memory fail\n");
}
else
{
do
{
printf("number:\n");
if (1 != scanf("%d", &op)) break;
if (op >= 0) {
// Realloc a new block of tam bytes if out of space
if (*nElem >= items_allocated) {
items_allocated += *tam;
int *temp = realloc(*lista, items_allocated * sizeof(int));
if (temp == NULL) {
printf("memory fail");
break;
}
else {
*lista = temp;
printf("added: %zu bytes total: %zu bytes\n", *tam * sizeof(int), items_allocated * sizeof(int));
}
}
(*lista)[*nElem] = op;
(*nElem)++;
}
} while (op >= 0);
}
}
int main(int argc, char** argv) {
int *lista = NULL, nElem = 0, tam = 5;
leNumeros(&lista, &nElem, &tam);
for (int i = 0; i < nElem; i++) {
printf("%d ", lista[i]);
}
return (EXIT_SUCCESS);
}

Related

What's wrong with my realloc doing on 2d-array

I am solving binary tree paths leet code programming question 257. I am having issue for one of the larger input where my code is getting segmentation fault. I suspect that there is an problem with my realloc but I am not able to figure it out.
Below is my approach:
Initially I started by dynamically allocating 80 bytes of memory of type char (80/8 = 10 rows)and storing the returned address to char **res variable.
char ** res = (char **)malloc(sizeof(char *) * sum);
I am calling findpath function recursively to find all the binary tree paths. Whenever one path is found , I dynamic allocate 100 bytes for each row index.
res[resIdx] = (char *)malloc(sizeof(char) * 100);
I have one global variable resIdx which points to the current row index where I copy the found binary tree path and increment the global variable resIdx.
if the resIdx becomes greater then total number of rows which was previously allocated then I do realloc of the memory but it looks like realloc is getting failed.
if (resIdx >= sum)
{
sum = sum + 10;
res = (char **)realloc(res,sizeof(char *) * sum); //Any issue here?
}
Can anyone please help me to figure out what's wrong I am doing in my code. Below is my full code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int sum;
int resIdx;
void findpath (struct TreeNode* root, int *ls,int ls_idx,char **res);
char ** binaryTreePaths(struct TreeNode* root, int* returnSize){
if (root == NULL)
{
*returnSize = 0;
return NULL;
}
resIdx = 0;
sum = 10;
char ** res = (char **)malloc(sizeof(char *) * sum);
int ls[100];
findpath(root,&ls[0],0,res);
*returnSize = resIdx;
return &res[0];
}
void findpath (struct TreeNode* root, int *ls,int ls_idx,char **res)
{
char temp[100];
int l=0,i=0;
if (root->left == NULL && root->right == NULL)
{
ls[ls_idx] = root->val;
ls_idx+=1;
if (resIdx >= sum)
{
sum = sum + 10;
res = (char **)realloc(res,sizeof(char *) * sum);
}
res[resIdx] = (char *)malloc(sizeof(char) * 100);
while (i < ls_idx)
{
if (i==0)
{
l = l + sprintf(&temp[l], "%d", ls[i]);
}
else
{
l = l + sprintf(&temp[l], "->%d", ls[i]);
}
i++;
}
strcpy(res[resIdx],temp);
resIdx++;
return;
}
ls[ls_idx] = root->val;
if (root->left != NULL)
{
findpath(root->left,ls,ls_idx+1,res);
}
if (root->right != NULL)
{
findpath(root->right,ls,ls_idx+1,res);
}
return;
}
The last argument to your findPath function is declared as a char** type; thus, when you make the call findpath(root,&ls[0],0,res); in binaryTreePaths, where the res variable is a char** type, a copy of that pointer is passed to the findPath function (most likely, but not necessarily, by placing that copy on the stack).
Then, if reallocation is required, the res = (char **)realloc(res,sizeof(char *) * sum); line in that function overwrites the value in the passed copy and, at the same time (if the call is successful – vide infra), will (probably) invalidate (i.e. free) the memory referenced by the previous address in that res copy. Thus, when control returns to the calling binaryTreePaths function, its own version of res will not have been modified and will remain pointing to that (now invalid) memory.
So, in order for your findPath function to be able to modify the given res argument, that must be passed as a pointer – in this case, a pointer to a char**, which will be of type char***; then, when called, you will need to pass the address of the res variable in binaryTreePaths.
Note also that directly overwriting a pointer in a call to realloc, as you have done in the line of code quoted above is dangerous. This is because, should that call fail, then you have lost the original data pointer (it will have been overwritten with NULL) and error recovery will be very difficult. You should save the return value in a temporary variable and only replace your original if the call succeeds.
With the code you have provided, I cannot properly test for any other errors but, taking the points above in hand, the below is a possible fix. See also: Do I cast the result of malloc?
int sum;
int resIdx;
void findpath(struct TreeNode* root, int* ls, int ls_idx, char*** res); // Note last argument type!
char** binaryTreePaths(struct TreeNode* root, int* returnSize)
{
if (root == NULL) {
*returnSize = 0;
return NULL;
}
resIdx = 0;
sum = 10;
char** res = malloc(sizeof(char*) * sum);
int ls[100];
findpath(root, &ls[0], 0, &res); // Pass ADDRESS of res
*returnSize = resIdx;
return &res[0];
}
void findpath(struct TreeNode* root, int* ls, int ls_idx, char*** res)
{
char temp[100];
int l = 0, i = 0;
if (root->left == NULL && root->right == NULL) {
ls[ls_idx] = root->val;
ls_idx += 1;
if (resIdx >= sum) {
sum = sum + 10;
char** test = realloc(*res, sizeof(char*) * sum);
if (test == NULL) {
// Handle/signal error
return;
}
*res = test; // Only replace original if realloc succeeded!
}
(*res)[resIdx] = malloc(sizeof(char) * 100);
while (i < ls_idx) {
if (i == 0) {
l = l + sprintf(&temp[l], "%d", ls[i]);
}
else {
l = l + sprintf(&temp[l], "->%d", ls[i]);
}
i++;
}
strcpy((*res)[resIdx], temp);
resIdx++;
return;
}
ls[ls_idx] = root->val;
if (root->left != NULL) {
findpath(root->left, ls, ls_idx + 1, res);
}
if (root->right != NULL) {
findpath(root->right, ls, ls_idx + 1, res);
}
return;
}

asprint memory leak need help understand where leak is coming from and possible fixes

Note: I did call this function and free it main but valgrind still shows error.
This code basically takes in a singly linked-list with two data coeff and exp. This is basically converting a polynomial store in a linked list converted to readable string. I looking to have it dynamic allocated.
char *Poly_to_string(const Polynomial *p)
{
char *x = malloc(1);
int size;
while (p != NULL)
{
if((p->exp != 0) && (p->exp != 1))
{
size = asprintf(&x, "%s%dx^%d + ", x, p->coeff, p->exp);
if (size == -1)
{
exit(-1);
}
}
else if(p->exp == 1)
{
size = asprintf(&x, "%s%dx + ", x, p->coeff);
if (size == -1)
{
exit(-1);
}
}
else if(!p->exp)
{
size = asprintf(&x, "%s%d + ", x, p->coeff);
if (size == -1)
{
exit(-1);
}
}
p = p->next;
}
x[strlen(x) - 3] = '\0';
return x;
}
From the Linux asprintf() man page (bolding mine):
DESCRIPTION
The functions asprintf() and vasprintf() are analogs of
sprintf(3) and vsprintf(3), except that they allocate a string
large enough to hold the output including the terminating null
byte ('\0'), and return a pointer to it via the first argument.
This pointer should be passed to free(3) to release the allocated
storage when it is no longer needed.
RETURN VALUE
When successful, these functions return the number of bytes
printed, just like sprintf(3). If memory allocation wasn't
possible, or some other error occurs, these functions will return
-1, and the contents of strp are undefined.
This line is wrong:
char *x = malloc(1);
It should just be
char *x;
because if asprintf() works, it will overwrite the contents of x and cause the memory allocated in char *x = malloc(1); to be leaked.
EDIT
The looping also needs to be addressed, as you're trying to grow the string:
char *Poly_to_string(const Polynomial *p)
{
// start with an empty string that can be free()'d
// (if you don't have strdup() use malloc() and strcpy())
char *x = strdup("");
int size;
while (p != NULL)
{
// save the old malloc()'d value so it can be free()'d
char *oldValue = x;
if((p->exp != 0) && (p->exp != 1))
{
size = asprintf(&x, "%s%dx^%d + ", x, p->coeff, p->exp);
if (size == -1)
{
exit(-1);
}
}
else if(p->exp == 1)
{
size = asprintf(&x, "%s%dx + ", x, p->coeff);
if (size == -1)
{
exit(-1);
}
}
else if(!p->exp)
{
size = asprintf(&x, "%s%d + ", x, p->coeff);
if (size == -1)
{
exit(-1);
}
}
// free() the old value
free(oldValue);
p = p->next;
}
x[strlen(x) - 3] = '\0';
return x;
}
There are other ways to do this without the initial char *x = strdup(""); but the code then becomes a lot more complex.
You're not deallocating variable x

Resizing 2D char array causes exception

I'm new to C, so please forgive me for noobie mistakes, we all need to start somewhere.
My task is to get some lines from a big file and store each line in a 2d array, where li[0] is the first line and so on...
On top of that, I have no ideia whats the size of this 'big text', so I came up with the code bellow to resize the array every time it reaches critical size (is there an easier way to do that?). Also, I could not find a better way to define the line size other than setting it very high.
The code bellow fails on the second time it resizes with an exception on this line char **temp = realloc(lin, LINE_QUANT * sizeof(char*));
Whats causing that exception?
#include <stdio.h>
#include <stdlib.h>
#define LINE_TAM 200
size_t PAL_QUANT = 100, LINE_QUANT = 3;
int main(){
int i = 0;
char **li = (char**) malloc(LINE_QUANT * sizeof(char*));
char fname[30];
FILE *arq = NULL;
// alloc word container
for (i=0; i < LINE_QUANT; i++)
li[i] = malloc(LINE_TAM * sizeof(char));
if(li == NULL) return 0;
//(ommited file opener)
i = 0;
//getting words from file (unknown size)
while(fgets(li[i], LINE_TAM, arq) != NULL){
while(i >= LINE_QUANT - 1) resizeArr(li);
i++;
}
return 1;
}
void resizeArr(char **lin){
int i;
LINE_QUANT = LINE_QUANT * 2;
char **temp = realloc(lin, LINE_QUANT * sizeof(char*));
if(temp) {
lin = temp;
for (i = LINE_QUANT/2; i < LINE_QUANT; i++){
lin[i] = malloc(LINE_TAM * sizeof(char*));
if (lin[i] == NULL)
exit(1);
}
}
else
exit(1);
free(temp);
}
Since each element of the array will be the same size, use could be made of a pointer to array, (*li)[LINE_TAM].
Because resizeArr modifies the pointer, either a pointer to the pointer needs to be passed to the function or the function needs to return the pointer.
realloc will take care of any required free, so do not free the pointers.
This uses stdin but it can be modified to use a FILE*.
Enter stop to exit the loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_TAM 200
void resizeArr ( size_t *line_quant, char (**lin)[LINE_TAM]);
int main(){
int i = 0;
char (*li)[LINE_TAM] = NULL;//pointer to array
size_t Line_Quant = 3;
// alloc word container
if ( NULL == ( li = malloc( sizeof *li * Line_Quant))) {
fprintf ( stderr, "malloc problem\n");
return 1;
}
i = 0;
//getting words from file (unknown size)
while ( fgets ( li[i], LINE_TAM, stdin) != NULL) {
if ( 0 == strcmp ( li[i], "stop\n")) {
break;
}
if (i >= Line_Quant - 1) {
resizeArr ( &Line_Quant, &li);
}
i++;
}
free ( li);
return 1;
}
void resizeArr ( size_t *line_quant, char (**lin)[LINE_TAM]) {
int i;
char (*temp)[LINE_TAM] = realloc ( *lin, sizeof **lin * *line_quant * 2);
if ( temp) {//success
*lin = temp;//assign back to caller
*line_quant *= 2;//increase by two
for ( i = *line_quant / 2; i < *line_quant; i++) {
(*lin)[i][0] = 0;
}
}
else {
fprintf ( stderr, "realloc problem\n");
}
}

Having trouble when allocating memory when passing a double pointers address into a triple pointer

I'm creating a double pointer and sending in the address to allocate memory, which requires a triple pointer. Also, i am creating single pointers (goals and assists) and sending their addresses to allocate memory, which requires double pointers. I think the problem lies in allocation of memory, but i cant figure it out. I keep seg faulting whenever i run the readLinesFromFile function. It does not segfault when I try running allocateMemory function by itself. The problem could also be in the readLinesFromFile function
int main (int argc, char **argv)
{
int numPlayers = 0;
if (argc != 3)
{
printf("Missing text file");
return 0;
}
char **playerNames;
int *goals, *assists;
FILE *filePtr = fopen(argv[1],"r");
if(filePtr == NULL)
{
printf("\nFile is empty");
return 0;
}
numPlayers = countLinesInFile(filePtr);
allocateMemory(&goals,&assists,&playerNames,numPlayers);
readLinesFromFile(filePtr,goals,assists,playerNames,numPlayers);
}
void allocateMemory(int **goals, int **assists, char *** names, int size)
{
int i = 0;
*goals = malloc(MAX_NAME * sizeof(int));
*assists = malloc(MAX_NAME * sizeof(int));
*names = malloc(MAX_NAME * sizeof(char*));
for (i = 0; i < size; i++)
{
(names[i]) = malloc(MAX_NAME * sizeof(char*));
}
}
void readLinesFromFile(FILE *fptr, int *goals, int *assists, char **names, int numLines)
{
int i = 0, j = 0, x = 0;
char players[MAX_LINE];
char *tokenPtr;
fptr = fopen(INPUT,"r");
for(i = 0; i < numLines; i++)
{
fgets(players,MAX_LINE, fptr);
tokenPtr = strtok(players," ");
strcpy((*(names+i)), tokenPtr);
while (tokenPtr != NULL)
{
tokenPtr = strtok(NULL," ");
if (x = 0)
{
goals[i] = atoi(tokenPtr);
x = 1;
}
else
{
assists[i] = atoi(tokenPtr);
x = 0;
}
}
}
}
Assuming MAX_NAME is the maximum length of a player's name, this should work:
void AllocateMemory(char *** pppNames, int ** ppGoals, int ** ppAssists, size_t sizePlayersMax)
{
*pppNames = malloc(sizePlayersMax * sizeof **pppNames);
*ppGoals = malloc(sizePlayersMax * sizeof **ppGoals);9
*ppAssists = malloc(sizePlayersMax * sizeof **ppAssists);
{
size_t sizePlayersCount = 0;0
for (; sizePlayersCount < sizePlayersMax; ++sizePlayersCount)
{
(*pppNames)[sizePlayersCount] = calloc(MAX_NAME + 1, sizeof *((*pppNames)[sizePlayersCount]));
}
}
}
To prevent the app from overwriting memory in case of really long player names you might like to change this line:
strcpy((*(names+i)), tokenPtr);
to become:
if (tokenPtr)
strncpy((*(names+i)), tokenPtr, MAX_NAME);
This would truncate the player names stored to a maximum of MAX_NAME characters. The latter is the size AllocateMemory() use minus 1. This one spare character is needed for the 0/NUL to terminate the character-array so it could be used as a "string".
Finally also this is dangerous:
while (tokenPtr != NULL)
{
tokenPtr = strtok(NULL," ");
if (x = 0)
{
Better do like this:
while (NULL != (tokenPtr = strtok(NULL," ")))
{
if (x = 0)
{

Program Segmentation Faults on return 0/fclose/free. I think I have memory leaks but can't find them. Please help!

I am trying to write a Huffman encoding program to compress a text file. Upon completetion, the program will terminate at the return statement, or when I attempt to close a file I was reading from. I assume I have memory leaks, but I cannot find them. If you can spot them, let me know (and a method for fixing them would be appreciated!).
(note: small1.txt is any standard text file)
Here is the main program
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ASCII 255
struct link {
int freq;
char ch[ASCII];
struct link* right;
struct link* left;
};
typedef struct link node;
typedef char * string;
FILE * ofp;
FILE * ifp;
int writebit(unsigned char);
void sort(node *[], int);
node* create(char[], int);
void sright(node *[], int);
void Assign_Code(node*, int[], int, string *);
void Delete_Tree(node *);
int main(int argc, char *argv[]) {
//Hard-coded variables
//Counters
int a, b, c = 0;
//Arrays
char *key = (char*) malloc(ASCII * sizeof(char*));
int *value = (int*) malloc(ASCII * sizeof(int*));
//File pointers
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "can't open %s\n", argv[1]);
return 0;
}
//Nodes
node* ptr;//, *head;
node* array[ASCII];
//
int u, carray[ASCII];
char str[ASCII];
//Variables
char car = 0;
int inList = 0;
int placeinList = -1;
int numofKeys;
if (argc < 2) {
printf("Usage: huff <.txt file> \n");
return 0;
}
for (a = 0; a < ASCII; a++) {
key[a] = -1;
value[a] = 0;
}
car = fgetc(fp);
while (!feof(fp)) {
for (a = 0; a < ASCII; a++) {
if (key[a] == car) {
inList = 1;
placeinList = a;
}
}
if (inList) {
//increment value array
value[placeinList]++;
inList = 0;
} else {
for (b = 0; b < ASCII; b++) {
if (key[b] == -1) {
key[b] = car;
break;
}
}
}
car = fgetc(fp);
}
fclose(fp);
c = 0;
for (a = 0; a < ASCII; a++) {
if (key[a] != -1) {
array[c] = create(&key[a], value[a]);
numofKeys = c;
c++;
}
}
string code_string[numofKeys];
while (numofKeys > 1) {
sort(array, numofKeys);
u = array[0]->freq + array[1]->freq;
strcpy(str, array[0]->ch);
strcat(str, array[1]->ch);
ptr = create(str, u);
ptr->right = array[1];
ptr->left = array[0];
array[0] = ptr;
sright(array, numofKeys);
numofKeys--;
}
Assign_Code(array[0], carray, 0, code_string);
ofp = fopen("small1.txt.huff", "w");
ifp = fopen("small1.txt", "r");
car = fgetc(ifp);
while (!feof(ifp)) {
for (a = 0; a < ASCII; a++) {
if (key[a] == car) {
for (b = 0; b < strlen(code_string[a]); b++) {
if (code_string[a][b] == 48) {
writebit(0);
} else if (code_string[a][b] == 49) {
writebit(1);
}
}
}
}
car = fgetc(ifp);
}
writebit(255);
fclose(ofp);
ifp = fopen("small1.txt", "r");
fclose(ifp);
free(key);
//free(value);
//free(code_string);
printf("here1\n");
return 0;
}
int writebit(unsigned char bitval) {
static unsigned char bitstogo = 8;
static unsigned char x = 0;
if ((bitval == 0) || (bitval == 1)) {
if (bitstogo == 0) {
fputc(x, ofp);
x = 0;
bitstogo = 8;
}
x = (x << 1) | bitval;
bitstogo--;
} else {
x = (x << bitstogo);
fputc(x, ofp);
}
return 0;
}
void Assign_Code(node* tree, int c[], int n, string * s) {
int i;
static int cnt = 0;
string buf = malloc(ASCII);
if ((tree->left == NULL) && (tree->right == NULL)) {
for (i = 0; i < n; i++) {
sprintf(buf, "%s%d", buf, c[i]);
}
s[cnt] = buf;
cnt++;
} else {
c[n] = 1;
n++;
Assign_Code(tree->left, c, n, s);
c[n - 1] = 0;
Assign_Code(tree->right, c, n, s);
}
}
node* create(char a[], int x) {
node* ptr;
ptr = (node *) malloc(sizeof(node));
ptr->freq = x;
strcpy(ptr->ch, a);
ptr->right = ptr->left = NULL;
return (ptr);
}
void sort(node* a[], int n) {
int i, j;
node* temp;
for (i = 0; i < n - 1; i++)
for (j = i; j < n; j++)
if (a[i]->freq > a[j]->freq) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
void sright(node* a[], int n) {
int i;
for (i = 1; i < n - 1; i++)
a[i] = a[i + 1];
}
If your program is crashing on what is otherwise a valid operation (like returning from a function or closing a file), I'll near-guarantee it's a buffer overflow problem rather than a memory leak.
Memory leaks just generally mean your mallocs will eventually fail, they do not mean that other operations will be affected. A buffer overflow of an item on the stack (for example) will most likely corrupt other items on the stack near it (such as a file handle variable or the return address from main).
Probably your best bet initially is to set up a conditional breakpoint on writes to the file handles. This should happen in the calls to fopen and nowhere else. If you detect a write after the fopen calls are finished, that will be where your problem occurred, so just examine the stack and the executing line to find out why.
Your first problem (this is not necessarily the only one) lies here:
c = 0;
for (a = 0; a < ASCII; a++) {
if (key[a] != -1) {
array[c] = create(&key[a], value[a]);
numofKeys = c; // DANGER,
c++; // WILL ROBINSON !!
}
}
string code_string[numofKeys];
You can see that you set the number of keys before you increment c. That means the number of keys is one less than you actually need so that, when you access the last element of code_string, you're actually accessing something else (which is unlikely to be a valid pointer).
Swap the numofKeys = c; and c++; around. When I do that, I at least get to the bit printing here1 and exit without a core dump. I can't vouch for the correctness of the rest of your code but this solves the segmentation violation so anything else should probably go in your next question (if need be).
I can see one problem:
strcpy(str, array[0]->ch);
strcat(str, array[1]->ch);
the ch field of struct link is a char array of size 255. It is not NUL terminated. So you cannot copy it using strcpy.
Also you have:
ofp = fopen("small1.txt.huff", "w");
ifp = fopen("small1.txt", "r");
If small1.txt.huff does not exist, it will be created. But if small1.txt it will not be created and fopen will return NULL, you must check the return value of fopen before you go and read from the file.
Just from counting, you have 4 separate malloc calls, but only one free call.
I would also be wary of your sprintf call, and how you are actually mallocing.
You do an sprintf(buf, "%s%d", buf, c[i]) but that can potentially be a buffer overflow if your final string is longer than ASCII bytes.
I advise you to step through with a debugger to see where it's throwing a segmentation fault, and then debug from there.
i compiled the program and ran it with it's source as that small1.txt file and got "can't open (null)" if the file doesn't exist or the file exist and you give it on the command like ./huf small1.txt the program crashes with:
Program terminated with signal 11, Segmentation fault.
#0 0x08048e47 in sort (a=0xbfd79688, n=68) at huf.c:195
195 if (a[i]->freq > a[j]->freq) {
(gdb) backtrace
#0 0x08048e47 in sort (a=0xbfd79688, n=68) at huf.c:195
#1 0x080489ba in main (argc=2, argv=0xbfd79b64) at huf.c:99
to get this from gdb you run
ulimit -c 100000000
./huf
gdb --core=./core ./huf
and type backtrace
You have various problems in your Code:
1.- mallocs (must be):
//Arrays
char *key = (char*) malloc(ASCII * sizeof(char));
int *value = (int*) malloc(ASCII * sizeof(int));
sizeof(char) == 1, sizeof(char *) == 4 or 8 (if 64 bits compiler is used).
2.- Buffer sizes 255 (ASCII) is too short to receive the contents of array[0]->ch + array[1]->ch + '\0'.
3.- Use strncpy instead of strcpy and strncat instead of strcat.
4.- key is an array of individuals chars or is a null terminated string ?, because you are using this variable in both ways in your code. In the characters counting loop you are using this variables as array of individuals chars, but in the creation of nodes you are passing the pointer of the array and copying as null terminated array.
5.- Finally always check your parameters before used it, you are checking if argc < 2 after trying to open argv[1].

Resources