この動的な再割り当てをポータブルな方法で機能させようとしています。
私のプログラムは、ユーザーからのテキスト行を受け取り、それをバッファーに追加します。バッファー内のテキストの長さが 20 以上の場合、最初の 20 文字を削除し、それ以降のすべての文字をバッファーの先頭に移動します。
Linux では問題なく動作するこのコードがありますが、Windows で実行するとガベージが発生します。mallocのみを使用してこれをポータブルにする理由/方法を知っている人はいますか? IE は string.h(strcpy) str を使用していません... len 以外のもの。
c17 のみ - 壊れたスタックはありません (ポータブルではありません)。これが私のコードです。エラーなしで gcc 7.3、mingw 7.3 をコンパイルします。get と put をより安全な関数に置き換えましたが、それでもウィンドウにガベージが表示されます。これはフォーマットの問題だと思います...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
void wbuff (message)
char *message;
{
FILE *f = fopen("file.txt", "w");
fprintf(f, "%s", message);
fclose(f);
}
char *rean (message)
char *message;
{
/* performs (write) on buffer, trims lefover, then restores */
char buf[80] = "";
puts("enter a line");
gets(buf);
int bln = strlen( buf );
int mln = strlen( message );
int nln = bln + mln;
printf("new length %d\n", nln);
message = realloc(message, nln);
memmove(message + mln, buf, bln);
/* MISTAKE IS HERE?! */
if( nln >= 20 ) {
int exl = nln -20; // leftover length
char *lo = realloc(NULL, exl); // leftover placeholder
memmove(lo, message+20, exl); // copy leftover
wbuff(message); // write clear buff
message = realloc(NULL, nln);
message = realloc(NULL, exl); // resize buffer
memmove(message, lo, exl); // restore leftover
}
return message;
}
void main (void)
{
char *message = "";
message = realloc(NULL, 0);
while ( 1 == 1 ) {
message = rean( message );
puts(message);
}
return;
}