Heap memory

This code should create a cell in the heap memory.(creatBox function)
And afterwards the function addNumber should add cell to the first pointer(*box)
with the value that user input.
It dosnt work after compile. would love to get some help. where i got wrong?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>


unsigned int* createBox();
void destructBox(unsigned int* box_ptr);
unsigned int* addNumber( unsigned int* box_ptr, unsigned int number);


int main()
{

unsigned int* box;
box = createBox();

int a;
 for(a=0; a<10; a++)
 {
   box = addNumber( box, 2);

    printf("%d ", *(box+a));

 }


destructBox(box);
    return 0;
}

unsigned int* createBox()
{

    return calloc(1, 4);
}

void destructBox(unsigned int* box_ptr)
{
    free(box_ptr);
}

unsigned int* addNumber( unsigned int* box_ptr, unsigned int number)
{

  *box_ptr += 1;           
   int a=4*(*box_ptr);
   box_ptr = (unsigned int *)realloc(box_ptr, a);
   if(box_ptr==NULL)
    printf("no more memory");
 *(box_ptr+(*box_ptr)) = number;


   return box_ptr;

}
You should be using the sizeof operator rather than just the magic number 4 (or what you have done on line 45) to indicate the number of bytes each element of the array is.

What exactly are you trying to do with your addNumber function?
Topic archived. No new replies allowed.