1

I try realloc but it didn't work

this is the code. thanks for your help

trial = malloc (4 * sizeof(int));

trial[0] = 1; trial[1] = 4;trial[2] = 7;trial[3] = 11;

trial = (int*)realloc(trial, sizeof(int) * 5);
trial[sizeof(trial)-1] = 23;

int a;
for(a = 0; a < sizeof(trial); a++){
        printf("TRIAL %d \n", trial[a]);
}

And the output look like this

TRIAL 1 
TRIAL 4 
TRIAL 7 
TRIAL 23 

It should be

TRIAL 1 
TRIAL 4 
TRIAL 7 
TRIAL 11
TRIAL 23 
1
  • You even said C in the title; why tag it as C++? Commented Nov 1, 2010 at 4:41

5 Answers 5

6

The problem is that sizeof does not tell you how many elements are in the array; it tells you how much space the pointer (which points to the first element) takes up. So sizeof(trial) == sizeof(int*), and not the number of elements. You need to store the length separately.

Sign up to request clarification or add additional context in comments.

1 Comment

You might also observe that @Scicare would have gotten totally different results on a 64-bit machine instead of the 32-bit machine where he was building (or with a 64-bit build).
2

sizeof will return sizeof(int *), which is the size of the pointer. You will have to keep track of the size of the pointer seperately.

Also, you should not return realloc() to the pointer you are reallocating. If realloc returns NULL, it will not modify the pointer and you will lose it. It is best to use a temporary pointer as follows:

int *p;
int *tmp;
/*...*/
tmp = realloc(p, NEW_SIZE);
if (tmp != NULL) p = tmp;
else { /*...*/ }

Comments

2

sizeof() on dynamically allocated memory only returns the size of the type, not the size of the block allocated. So sizeof(trial) in this case will return 4, the size of an int*.

Comments

2

sizeof(trial) == a constant (probably 4 or 8). It won't be the count of elements you allocated.

You need something like

int n = 100;
trial = realloc(trial, n*sizeof(*trial));

trial[n-1] = K;  // K is some number.

Comments

1

sizeof returns the size of the type, in this case the size of an int * which I assume is 4 bytes. So you are making the array size 5, but you are setting element (4 - 1) to 23. You'll need to keep track of the size of the array through a variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.