summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md1
-rw-r--r--calloc.c23
-rw-r--r--malloc.c21
-rw-r--r--memset.c19
-rw-r--r--realloc.c22
5 files changed, 86 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b036340
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+# cmem
diff --git a/calloc.c b/calloc.c
new file mode 100644
index 0000000..1f3bf66
--- /dev/null
+++ b/calloc.c
@@ -0,0 +1,23 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int main()
+{
+ char *mem_allocation;
+
+ // 動的メモリ確保(0で初期化)
+ mem_allocation = calloc(20, sizeof(char));
+ if (mem_allocation == NULL) {
+ fprintf(stderr, "メモリ確保失敗\n");
+ return 1;
+ } else {
+ mem_allocation[0] = 't';
+ mem_allocation[1] = 'e';
+ mem_allocation[2] = 's';
+ mem_allocation[3] = 't';
+ }
+
+ printf("格納した文字列 : %s\n", mem_allocation);
+ free(mem_allocation);
+ // => test
+}
diff --git a/malloc.c b/malloc.c
new file mode 100644
index 0000000..8bb81a1
--- /dev/null
+++ b/malloc.c
@@ -0,0 +1,21 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main()
+{
+ char *mem_allocation;
+
+ // 動的メモリ確保
+ mem_allocation = malloc(20 * sizeof(char));
+ if (mem_allocation == NULL) {
+ fprintf(stderr, "動的メモリ確保失敗\n");
+ return 1;
+ } else {
+ strlcpy(mem_allocation, "Hi, My sweet hearts", 20);
+ }
+
+ printf("格納した文字列 : %s\n", mem_allocation);
+ // => "Hi, My sweet hearts"
+ free(mem_allocation);
+}
diff --git a/memset.c b/memset.c
new file mode 100644
index 0000000..06db271
--- /dev/null
+++ b/memset.c
@@ -0,0 +1,19 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int main()
+{
+ int i;
+ char *a = malloc(5 * sizeof(char));
+
+ // 配列の要素を全て0に設定
+ memset(a, 0, 5*sizeof(char));
+
+ for (i = 0; i < 5; ++i) {
+ printf("a[%d] = %d,", i, a[i]);
+ }
+
+ // => a[0] = 0, a[1] = 0, a[2] = 0, a[3] = 0, a[4] = 0,
+ free(a);
+}
diff --git a/realloc.c b/realloc.c
new file mode 100644
index 0000000..e0caf86
--- /dev/null
+++ b/realloc.c
@@ -0,0 +1,22 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int main()
+{
+ char *mem_allocation;
+
+ // 動的メモリ確保
+ mem_allocation = malloc(20 * sizeof(char));
+ if (mem_allocation == NULL) {
+ fprintf(stderr, "メモリ確保失敗\n");
+ return 1;
+ }
+
+ // 動的メモリ再確保
+ mem_allocation = realloc(mem_allocation, 40 * sizeof(char));
+ if (mem_allocation == NULL) {
+ fprintf(stderr, "メモリ確保失敗\n");
+ return 1;
+ }
+ free(mem_allocation);
+}