D
D
DVoropaev2017-08-31 23:42:34
linux
DVoropaev, 2017-08-31 23:42:34

Why is gcc asking to include stdlib.h?

#include <stdio.h>
//#include <stdlib.h>
void print(int *p){
  for(int i = 0; i < 10; i++)
    printf("%i ", *(p+i));
}

int main(){
  int *p = malloc(45);
  for(int i = 0; i < 10; i++)
    *(p+i) = i*i;
  print(p);
  return 0;
}


$gcc ./main.c
./main.c: In function 'main':
./main.c:9:11: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
int *p = malloc(45);
^
./main.c:9:11: warning: incompatible implicit declaration of built-in function 'malloc'
./main.c:9:11: note: include ' stdlib.h ' or provide a declaration of 'malloc'

But it still works:
$ ./a.out
0 1 4 9 16 25 36 49 64 81

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2017-09-01
@Mercury13

Since you have stdlib.h commented out, you probably know where malloc came from. Let's try to unwind the errors.
The compiler obviously knows where this malloc is lying around...
...but implicitly declares a function.
Implicit definition of int* malloc(int). Real void* malloc(size_t). It was necessary to convert (int*)malloc.
Why did it start anyway? But because on the target machine size_t = unsigned int, and the sizes of pointers are almost always the same. After the function was implicitly declared, the linker picked up the standard one in its place, and the calling conventions matched.

A
Alexey Skobkin, 2017-08-31
@skobkin

./main.c:9:11: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]

You are using the malloc() function which is declared in stdlib.h . Did you try reading the error?

D
Derevyanko Alexander, 2017-09-01
@dio4

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

void print(int *p){
  for(int i = 0; i < 10; i++)
    printf("%i ", *(p+i));
}

int main(){
  int i,  *p = (int *) malloc(sizeof(int) * 45);
  for(i = 0; i < 10; i++)
    *(p+i) = i*i;
  print(p);
  printf("%c", '\n');
  return 0;
}
/*
Вывод в консоли
$ gcc  -Wall malloc.c -o malloc
$ ./malloc
0 1 4 9 16 25 36 49 64 81 
*/
/*
И чтобы выучил матчасть!
Прототип malloc() 
void *malloc(size_t size);
*/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question