-4

My problem is that i am not sure how to allocate memory properly. I have researched it but to no avail. Some help regarding malloc would be great.

int main(int argc, char *argv[]) {

    int i, a[5000], c = 1, m, n, input;

    scanf("%d", &input);

    for (i = 0; i <= 9999; i += 2) {

        a[c] = i;
        c++;

    }

    for (n = 2; n < 1118; n++) {

        for (m = a[n]; m < a[5000]; m++) {

            a[m] = a[m+1];
        }
    }

    printf("%d", a[input]);

    free (*a);

    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    It seems that you didn't search very far. Did you look at SO documentation? https://stackoverflow.com/documentation/c/4726/memory-management#t=201610092024124038819 – Jens Gustedt Oct 09 '16 at 20:25

3 Answers3

2

First of all, C arrays have 0-based indexing. By setting the intial value of c to 1 and then using as index inside the loop, you're going off-by-one. This invokes undefined behavior.

After that, you don't need to do free (*a);, a is an array, not a pointer returned by a memory allocator functions, malloc() or family.

That said, in this code, *a does not give you a pointer, at all, it is same as a[0] which is of type int.

Finally, without any bound checking from user supplied value of input, using a[input] may very well be accessing out of bound memory, causing UB.

FWIW, passing a pointer to free() which is not returned previously by malloc() and family also invokes undefined behavior.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

'a' is allocated on stack therefore no need to free it.

You only need to free variables allocated by *alloc family of functions.

SneakyMummin
  • 683
  • 1
  • 11
  • 30
-1

malloc takes one argument - the number of bytes to allocate. It returns a void pointer (which is a pointer to a section of memory that can hold any data type).

Here's an example.

int *array = malloc(sizeof(int) * 10);

This allocates a 10-element array of integers. Note it leaves your data uninitialized, so the contents of the array are undefined. There's a function called calloc that does initialize it to zeros.

Also, a style tip. You might try to cast the result of a malloc call to a pointer for the type of data you will store in it (for example, int *array = (int *)malloc(sizeof(int) * 10);. This is frowned upon by C programmers for reasons explained in this post.

Community
  • 1
  • 1
anonymoose
  • 819
  • 2
  • 11
  • 25