C言語で以下のようなコードを書いております。
C
1 2#include <stdio.h> 3#include <stdlib.h> 4#include <string.h> 5#include <malloc.h> 6#define malloc_usable_size(a) _msize(a) 7 8/** 9 * @param int c 10 * @param char*[] 11 * @return int 12 */ 13int main (int c, char* param[]) { 14 15 16 char * open_file_path; 17 char* new_file_path; 18 if (c >= 3) { 19 open_file_path = param[1]; 20 new_file_path = param[2]; 21 } else { 22 printf("You need to input three parameter from console."); 23 exit(2); 24 } 25 int read_byte; 26 int read_count = 1; 27 int *ip = NULL; 28 char* save = NULL; 29 char* buffer = NULL; 30 char* return_c = NULL; 31 char* temp = NULL; 32 FILE* fp = NULL; 33 34 // ファイルの読み込みサイズは1MBに設定 35 read_byte = sizeof(char) * 1000000; 36 buffer = (char*) malloc (read_byte); 37 if (buffer == NULL) { 38 printf("This command failed to secure appropriate memory allocation."); 39 exit(2); 40 } 41 fp = fopen(open_file_path, "rb"); 42 int i = 1; // ファイルサイズ 43 int current_address = 0; 44 int res; 45 46 while(1) { 47 // ファイルの読み込み 48 res = fread(buffer, read_byte, read_count, fp); 49 if (res >= read_count) { 50 // ここで初めてメモリの動的確保 51 if (i == 1) { 52 // 初回のみ 53 temp = (char*)malloc(read_byte * i); 54 save = temp; 55 printf("\r\n"); 56 printf("%d", read_byte * i); 57 memmove(save + current_address, buffer, read_byte); 58 // 現在のアドレスの位置を保持 59 current_address = current_address + read_byte; 60 printf("1"); 61 } else { 62 temp = (char*)realloc((void*)save, read_byte * i); 63 printf("2"); 64 if (temp != NULL) { 65 if (save == temp) { 66 printf("\r\n"); 67 printf("Two addresses has same memory address."); 68 save = temp; 69 70 } else { 71 printf("\r\n"); 72 printf("Two addresses has different memory address."); 73 save = temp; 74 } 75 printf("\r\n"); 76 printf("%d", read_byte * i); 77 memmove(save + current_address, buffer, read_byte); 78 // 現在のアドレスの位置を保持 79 current_address = current_address + read_byte; 80 } else { 81 printf("You cannot get memory you commanded."); 82 printf("%d", read_byte); 83 exit(2); 84 } 85 } 86 } else { 87 break; 88 } 89 i++; 90 } 91 fclose(fp); 92 FILE* new_fp = NULL; 93 new_fp = fopen(new_file_path, "wb+"); 94 fwrite(save, _msize(save), read_count, new_fp); 95 fclose(new_fp); 96 exit(1); 97}
上記のコードは実行時の第一コマンドライン引数をコピーし,第二コマンドライン引数のファイル名を作成し
まるっと移す処理です。
実行したところファイル容量が大体550MBを超える動画ファイルなどのコピーを実行すると
途中でrealloc関数が必ずエラーになってしまいす。
このメモリ確保時のエラーについて回避する方法はないでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。