i am having trouble allocating space in my program.
and arent getting the results i would like.
here is my code:
Code:
int
main(int argc, char **argv)
{
int input;
/* Parse Arguments */
clo_t *iopts = parse_args(argc, argv);
FILE *fp = fopen(iopts->input_file,"r");
/* Use fscanf to read all data values into new set_t */
/*data_set*/
set_t * data_set = set_create(1000);
while(fscanf(fp, "%d", &input) != EOF)
{
printf("data items: %i\n", data_set->items);
printf("data: %i\n", data_set->data[data_set->items]);
set_insert(data_set, input, data_set->data);
}
return (EXIT_SUCCESS);
}
safe_malloc function i was provided with and the safe_realloc function i tried to make,
old_mem + 1000 dosnt seem right and i get a segfault when i try to use safe_realloc.
Code:
void *
safe_malloc(size_t size)
{
void *mem_block = NULL;
if ((mem_block = calloc(1, size)) == NULL) {
fprintf(stderr, "ERROR: safe_malloc(%zu) cannot allocate memory.",
size);
exit(EXIT_FAILURE);
}
return (mem_block);
}
void *
safe_realloc(void *old_mem, size_t new_size)
{
if(realloc(new_size, (old_mem + 1000) * sizeof(int)) == NULL)
{
printf("stderr, ERROR: safe_realloc cannot allocate memory.\n");
exit(EXIT_FAILURE);
}
return(new_size);
}
this is where i call safe_realloc
Code:
int
set_insert(set_t *set, int item, int *set_size)
{
if(set->lock == TRUE)
{
printf("Set locked. cannot be altered at this time\n");
return (TRUE);
}
if(set->items >= set->n_max)
{
/*realloc more space*/
set->data = safe_realloc(set_size, 1000 * sizeof(int));
set n_max to the new size*/
set->n_max = *set_size + 1000;
}
set->data[set->items] = item;
set->items++;
return (TRUE);
}
Code:
set_t *
set_create(int size)
{
printf("size: %d\n", size);
set_t * set = safe_malloc(sizeof(set_t));
set->data = safe_malloc(size * sizeof(int));
set->items = 0;
printf("items: %d\n", set->items);
set->n_max = size;
set->lock = FALSE;
return(set);
}
and the set_t struct is:
Code:
typedef struct
{
int *data;
int items;
int n_max;
int lock;
} set_t;
my program prints the data items from 1 - 1000, data = 0 every time except for the last when it equals 8201, and n_max = 1000. the numbers in the file go from 0 to 11000, and im supposed to keep reallocating more space until it is done reading them all. and i cant get data to equal the right thing. Any ideas?