Answer the question
In order to leave comments, you need to log in
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'
$ ./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
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.
./main.c:9:11: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
#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 questionAsk a Question
731 491 924 answers to any question