"Doesn't it already do all of this automatically or something? "
Not only does it not get done automatically, but you when you do it you need to make sure it gets done right. For example, if you have a character *pointer which you want to refer to a string, you get the length of the string, MemoryALLOCate it enough storage, then copy the string in:
Code:
#include <string.h>
#include <stdlib.h>
int main() {
char *string;
size_t len;
len = strlen("a string");
string=malloc(len+1);
strcpy(string, "a string");
puts(string);
}
But if there isn't enough memory, malloc will return a NULL pointer and you will get a segfault.
So always check by inserting something like this:
Code:
string=malloc(len+1);
if (string==NULL) puts("malloc error!");
You should actually just kill the program in that case, so to save yourself some time create an "error-checked malloc" function and use it instead of malloc:
Code:
void *ec_malloc (unsigned int bytes) {
void *assign;
assign = malloc(bytes);
if (assign == NULL) exit(-1);
return assign;
}
So now in main you can go:
string=ec_malloc(len+1);