Why does the return value of the function change when the number of bytes of malloc
is large?
func.c:
#include "func.h"
int *func()
{
int *ptr = (int *)malloc(100000000);
printf("ptr in func is %p \n", ptr);
return ptr;
}
func.h:
#ifndef _FUNC_H
#define _FUNC_H
#include <stdio.h>
#include <stdlib.h>
//int *func();
#endif
main.c
#include <stdio.h>
#include "func.h"
int main(int argc, char** argv)
{
int *ptr = func();
printf("ptr is %p \n", ptr);
}
compilation and run:
gcc -g main.c func.c -o main
the compilation result is:
main.c: In function ‘main’:
main.c:7:13: warning: implicit declaration of function ‘func’; did you mean ‘putc’? [-Wimplicit-function-declaration]
int* ptr = func();
^~~~
putc
main.c:7:13: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
run result:
ptr in func is 0x7f557ea88010
ptr is 0x7ea88010
Why does the function return the same value when the number of bytes of malloc
is small?
func.c
#include "func.h"
int *func()
{
int *ptr = (int *)malloc(100);
ptrintf("ptr in func is %p \n", ptr);
return ptr;
}
run result:
ptr in func is 0x17af2a0
ptr is 0x17af2a0
Can you tell me why? I want to know what exactly caused it?