Memory Allocation
Allocating and Deallocating, malloc() and free()
#include <stdio.h>#include <stdlib.h>
int main(){ int *p = malloc(10*(sizeof(int)));
for (int i = 0; i< 10; i++){ p[i] = i*5; }
for (int i = 0; i < 10; i++){ printf("%d\t", p[i]); } free(p);}
Alternative: calloc()
int *p = calloc(10, sizeof(int));//equivalent toint *p = malloc(10 * sizeof(int));
Changing Allocated size with realloc()
#include <stdio.h>#include <stdlib.h>
char *readline(FILE *fp){ int offset = 0; int bufsize = 4;
char *buf; int c; //char we read in
buf = malloc(bufsize); if (buf == NULL) { // Error check return NULL; }
while (c = fgetc(fp), c != '\n' && c != EOF){ if (offset == bufsize - 1) { char *new_buf = realloc(buf, offset * 2); if (new_buf == NULL){ free(buf); return NULL; } buf = new_buf; } buf[offset++] = c; }
//We hit new line or End of file
//If no char read, return null if (c == EOF && offset == 0){ free(buf); return NULL; }
if (offset < bufsize - 1){ char *new_buf = realloc(buf, offset + 1); if (new_buf != NULL){ buf = new_buf; } }
//Add the NUL terminator; buf[offset] = '\0';
return buf;}
int main(){ FILE *fp = fopen("../hello.txt","r");
char *line;
while (line = readline(fp), line != NULL){ printf("%s\n", line); free(line); } fclose(fp);}