Last active
September 8, 2020 15:25
-
-
Save skuralll/c4e34772bc0942352a925acd2e19cfb4 to your computer and use it in GitHub Desktop.
reallocできない
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
//Utils(ファイル分割すべきだけど設定がめんどくさいので) | |
typedef struct | |
{ | |
int len; | |
char str[]; | |
} istring; | |
istring* getIstring(char chars[], int length){ | |
istring* ret = malloc(sizeof(istring) + sizeof(char)*length); | |
ret->len = length; | |
strcpy(ret->str, chars); | |
return ret; | |
} | |
//プロトタイプ宣言 | |
char* lzw_c(char raw_c[], int length); | |
//メイン | |
int main(){ | |
char raw[] = "010101010"; | |
char* comped = lzw_c(raw, sizeof(raw) / sizeof(char)); | |
printf("%s\n", comped); | |
return 0; | |
} | |
//ユーザー定義関数 | |
char* lzw_c(char raw_c[], int length){ | |
istring* raw = getIstring(raw_c, length); | |
printf("arg|raw_c: %s\n", raw->str); | |
printf("arg|length: %d\n", raw->len); | |
istring *dic;//辞書 | |
int dic_pages = 0; | |
istring w = *getIstring("", 0); | |
istring k = *getIstring("", 0); | |
int exist_flag = 0; | |
//辞書の初期化処理 | |
for(int i = 0; i < length; i++){ | |
if(raw_c[i] == '\0') break; | |
//printf("arg|raw_c[%d]: %c\n", i, raw_c[i]); | |
//辞書にすでに登録されているか判定 | |
exist_flag = 0; | |
for(int j = 0; j < dic_pages; j++){ | |
if(dic[j].str[0] == raw_c[i]){ | |
exist_flag = 1; | |
break; | |
} | |
} | |
//辞書に登録されていなかったら,登録 | |
if(exist_flag == 0){ | |
printf("dic|register <%c> to page %d\n", raw_c[i], dic_pages); | |
printf("dic|old_size: %d\n", sizeof(*dic)); | |
printf("dic|pointer: %p\n", dic); | |
char newword[] = {raw_c[i]}; | |
istring* newpage = getIstring(newword, 1); | |
istring* temp = realloc(dic, sizeof(*dic) + sizeof(*newpage)); | |
printf("dic|new_size: %d\n", sizeof(*dic) + sizeof(*newpage)); | |
if(temp == NULL){ | |
printf("dic|ERROR OCCURED\n"); | |
exit(1); | |
}else{ | |
dic = temp; | |
dic[dic_pages] = *newpage; | |
dic_pages++; | |
} | |
} | |
} | |
return "Not implemented"; | |
} |
https://twitter.com/pepepper_cpp/status/1302257807094235136
https://t.co/Z55RCOR6mf?amp=1
フレキシブル配列メンバを含む構造体の配列は使ってはいけない
END
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
出力
arg|raw_c: 010101010
arg|length: 10
dic|register <0> to page 0
dic|old_size: 4
dic|pointer: 0061FFCC
dic|new_size: 8
dic|ERROR OCCURED