How do i make a dynamically allocated memory as a global memory location?
#include <stdio.h>
#include <string.h>
char* call(int);
char *y;
int main() {
char *a;
int x;
x=45;
a=call(x); \\ I guess it must be pointing to the Memory pointed by y
printf(a); \\prints hello world
x=46;
strcpy(a,"good");
a=call(x);
printf(a);
}
char* call(int x) {
y=(char *)malloc(40);
if(x==45) {
strcpy(y,"hello world");
return(y);
} else {
return(y);
}
}
I have some questions:
-
Does the memory alloacted by the
malloc()stay until the end of program or until the end of the function where it is defined? -
How do I make
aandypoint to the same address allocated by the malloc function when they are in different functions? -
How do I make the dynamically allocated memory globally accessible?
freeon that pointera = y;will makeaandypoint to the same memory location. In your case,a = call(x);does that too.apoints to the memory you allocated incallwhich is still valid inmain.Remember to
free(a);in yourmain.