commit dd9042cea8550135e40dc7e1dd9b90a63096e89e
parent 59fbab53ee580386a1601fea22d01f39ef861113
Author: Matsuda Kenji <info@mtkn.jp>
Date: Sun, 25 Jun 2023 18:43:05 +0900
allocate memory dynamically
Diffstat:
M | main.c | | | 36 | ++++++++++++++++++++++++++++++++---- |
1 file changed, 32 insertions(+), 4 deletions(-)
diff --git a/main.c b/main.c
@@ -36,19 +36,47 @@ readfile(const char *file)
return NULL;
}
- size_t bufsize = 1024;
+ size_t bufsize = 128;
+ size_t bytesRead = 0;
char *c;
c = (char *)malloc(bufsize);
+ if (c == NULL) {
+ snprintf(errstr, sizeof(errstr),
+ "allocate memory: errno = %d", errno);
+ return NULL;
+ }
- size_t read = fread(c, sizeof(c[0]), bufsize, f);
- if (read == sizeof(c)) {
+ for (;;) {
+ size_t read = fread(&c[bytesRead], sizeof(c[0]),
+ bufsize-bytesRead, f);
+ bytesRead += read;
+ if (read < bufsize - bytesRead) {
+ break;
+ }
+ bufsize *= 2; // TODO: check overflow.
+ char* newc = (char *)realloc(c, bufsize);
+ if (newc == NULL) {
+ snprintf(errstr, sizeof(errstr),
+ "allocate memory: errno = %d", errno);
+ free(c);
+ return NULL;
+ }
+ c = newc;
+ }
+ if (!feof(f) || ferror(f)) {
snprintf(errstr, sizeof(errstr),
- "read file: file too big: %s", file);
+ "read from file %s: errno = %d", file, errno);
+ free(c);
return NULL;
}
+
+ c[bytesRead] = '\0';
return c;
}
+// ShaderInit create Shader struct with vertexShader specified by vs and
+// fragmentShader specified by fs. vs and fs are path names to the shader
+// files. It returns the pointer to the resulting struct.
Shader *
ShaderInit(const char *vs, const char *fs)
{