Search code examples
cdynamic-memory-allocation

New to Dynamically memory "first time"


why the error

#include <stdio.h>

int main(void)
{
    int *p, size, i;
    FILE *fp;

    fp = fopen("input.txt","r");
    fscanf(fp, "%d", &size);

    p = (int*)malloc(size*sizeof(int));  //error
    for (i = 0; i <size; i++)
        fscanf(fp, "%d", &p[i]);

    for (i = size-1; i>= 0; i--)
        printf("%d\n", p[i]);

    free(p);
    fclose(fp);
    return 0;
}

i'm using "Geany" on ubuntu

and on Geany compiler :

fileName.c:11:2: warning implicit declaration of function 'malloc' [-Wimplicit-function-declatation] fileName.c:11:12: warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default] fileName.c:18:12: warning: implicit declaration of function 'free' [-Wimplicit-function-declaration] fileName.c:18:12: warning: incompatible implicit declaration of built-in function 'free' [enabled-by default] compilation finished successfully


Solution

  • You're missing the following header include:

    #include <stdlib.h>
    

    The prototypes for malloc and free are defined in the stdlib.h header file which you missed out.

    If you're unsure which header files to include for some standard C functions, you could always use man to figure it out.

    For this case man malloc would have shown the required header file to be included.

    BTW, in your code you're not checking if fp is NULL after fopen.

    fopen can and will fail if the file does not exist or you do not have permissions to open the file (for reading in your case).

    fp = fopen("input.txt","r");
    if (fp == NULL)
    {
        printf("Error opening input.txt\n");
        return -1;
    }