i don't understand the difference here:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *blah;
void getmem()
{
blah = malloc(10);
}
int main()
{
char buffer[10];
getmem();
fgets(buffer, sizeof buffer, stdin);
strcpy(blah, buffer);
puts(blah);
return 0;
}
in the above case the memory is apparently allocated inside getmem, then disappears once getmem returns, but in the below case...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ex {
char *ptr_1;
} whatever;
void getmem(struct ex *ptr)
{
ptr->ptr_1 = malloc(10);
}
int main()
{
struct ex *ptr_whatever;
char buffer[10];
ptr_whatever = &whatever;
getmem(ptr_whatever);
fgets(buffer, sizeof buffer, stdin);
strcpy(ptr_whatever->ptr_1, buffer);
puts(ptr_whatever->ptr_1);
return 0;
}
...the only difference i can see is that the pointer is stored within a structure but its memory is allocated so that it can still be used by main. in the first case strcpy causes a seg fault and in the second case everything works perfectly. why is this so?