Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to empty space in allocated memory?

Let's say I have something like this:

char *array,*mat;
array= (char*)malloc(BUFFER * sizeof(char));
fscanf("%s",array);
mat = (char*)malloc(strlen(array) * sizeof(char));
strcpy(mat1, strarr1);

So basically, I'm storing some text and then copying it over, but what happens if the original text is smaller than the BUFFER size? Does my original array occupy the size I allocated for it or does it only occupy the size of the string it contains?

like image 759
Henrique Avatar asked Nov 29 '25 11:11

Henrique


1 Answers

The original array doesn't change its size. It occupies the exact size you allocated for it.

The data your store in a memory location simply overwrites the bytes that were previously written in that location.

If you allocated more space than you're using (for your string), those extra bytes aren't touched and they keep the same data they had before.

If you allocated less space than you're using, then you have an overflow.

like image 110
jweyrich Avatar answered Dec 02 '25 03:12

jweyrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!