0

So if I have dinamically reserved memory for an array, in what adress do I have to make free of the array? Imagine if I did the following:

int *a = (int*)malloc(sizeof(int)*5);
// so now I have the following adress aviable: a, a+1, a+2, a+3 and a+4.
//in what adress should I make the free? What would happen if I make a free in a random adress like a+2?
free(a+2);
Elrisas
  • 49
  • 5
  • Almost certainly something bad. Pretty sure it's undefined. – Stephen Newell Jun 25 '22 at 18:47
  • The formal name for what you're doing it "undefined behavior" – Aykhan Hagverdili Jun 25 '22 at 18:48
  • so to free all the adresses of that array, I have to free only first adress? – Elrisas Jun 25 '22 at 18:49
  • 1
    Yes; there is only one **allocation**, so there should be exactly one deallocation. – Karl Knechtel Jun 25 '22 at 18:51
  • 1
    When you say `malloc(sizeof(int)*5)`, don't think of it as giving you "five addresses". Think of it as giving you five *integers*. Each of those integers has an address, of course, but that's not so interesting. (After all, just about every object you manipulate in your program has an address, whether that object came from a `malloc` call or not.) – Steve Summit Jun 25 '22 at 20:12
  • 1
    When it comes to freeing memory, the rule you want to think about is that, in general, you want your `free` calls to be one-to-one with your `malloc` calls. When you called `malloc(sizeof(int)*5)`, it gave you *one* pointer to *one* block of memory. So to free that block of memory, you want to call `free` precisely once, and most specifically, handing it precisely the one pointer that `malloc` initially returned to you. – Steve Summit Jun 25 '22 at 20:13
  • The argument to `free` must be the same pointer value returned from `malloc`. You don’t have to (and can’t) free each individual element of the array. – John Bode Jun 26 '22 at 11:41

0 Answers0