-1
#include <stdio.h>
#include <stdlib.h>

int tablou(n)
{
    int *buffer, i=0;
    buffer=(int*)malloc(n+1);
    if (buffer==NULL) exit(1);
    for(i=0; i<=n; i++){
        buffer[i]=i;
    printf ("%d ", buffer[i]);
    }
    //free(buffer);
    //printf("%d ", n);
    return 0;
}
int main()
{
    int n;
    printf("nr of elements:\n");
    scanf("%d", &n);
    tablou(n);
    printf("Hello world!\n");
    return 0;
}

it crashes at line 14:

free(buffer);

if I don't free the memory, the program gives an error after printing Hello world! if I free the memory, it gives an error before that.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
ClockWork
  • 3
  • 4

1 Answers1

4

Since malloc allocates space in bytes, and one integer is more than 1 byte wide, this

buffer = (int*)malloc(n+1);

should be

buffer = malloc((n+1) * sizeof(int));

You should allocate space for n + 1 integers. So you must multiply it by the size of the type.

A cleaner and more maintainable way to do it would be

buffer = malloc((n + 1) * sizeof(*buffer));
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • I'm wondering - how will the compiler understand how much data it should free with `free()` if the amount given in `malloc()` is dynamic? – Angivare Jan 26 '15 at 11:35
  • 3
    @Angivare that's a fair question to ask here. But probably not *right here*. – Drew Dormann Jan 26 '15 at 11:36
  • 2
    @Angivare The compiler doesn't. `malloc` keeps the number somewhere (usually at the addresses that come before the one it gives you) and `free` finds that number. – Theodoros Chatzigiannakis Jan 26 '15 at 11:38
  • 1
    @Angivare The compiler has nothing to do with it, the compiler isn't freeing any memory. The library code inside `free()` is doing that. Remember that `free()` is just a function, it's not part of the compiler. And the library does get the address of the memory to free, so it "just" has to have a way to associate that with the allocation size. That can be made in many, many ways. – unwind Jan 26 '15 at 11:38
  • @Anigivare , Read the last part of [dasblinkenlight's answer here](http://www.stackoverflow.com/questions/27675864/how-are-zero-length-arrays-in-a-structure-useful) – Spikatrix Jan 26 '15 at 11:39
  • @Angivare From the site's C FAQ: [How does free know how much to free?](http://stackoverflow.com/questions/1518711/how-does-free-know-how-much-to-free) – Lundin Jan 26 '15 at 12:12