だから私はプログラムを持っていて、その仕事はうまくいきます。
#include <stdio.h>
#include <stdlib.h>
#define STACKDEFSIZE 1
typedef struct
{
unsigned long int maxsize;
unsigned long int cursize;
unsigned long int* arr;
} stack;
stack* create_stack()
{
stack* res = (stack*)malloc(sizeof(stack));
res->arr = malloc(sizeof(long) * STACKDEFSIZE);
res->maxsize = STACKDEFSIZE;
res->cursize = 0;
return res;
}
void push(stack* st, int val)
{
if (st->cursize == st->maxsize)
{
unsigned long int* old = st->arr;
st->maxsize *= 2;
st->arr = malloc(sizeof(unsigned long int) * st->maxsize);
int i;
for(i = 0; i < st->cursize; i++)
st->arr[i] = old[i];
free(old);
}
st->arr[st->cursize] = val;
st->cursize += 1;
}
int main() {
stack* s = create_stack();
int i;
for(i = 0; i < 10000; i++)
{
push(s, i);
}
return 0;
}
しかし、mallocとfreeの代わりにreallocを使用するように関数 'push'を変更すると、プログラムがクラッシュし、「 `./t 'のエラー:realloc():次のサイズが無効です:0x0000000001031030中止されました」というメッセージが表示されます。
void push(stack* st, int val)
{
if (st->cursize == st->maxsize)
{
st->maxsize *= 2;
st->arr = realloc(st->arr, st->maxsize);
}
st->arr[st->cursize] = val;
st->cursize += 1;
}
また、reallocを使用しようとすると、valgrindの出力メッセージ「サイズ8の無効な書き込み」が表示されます。私は何を間違っていますか?私はgccとDebianJessiex86_64を使用しています。
に間違ったサイズを渡していますrealloc
。結果として、プログラムはすぐに未定義の動作に遭遇します。
使用する:
st->arr = realloc(st->arr, sizeof(*st->arr)*st->maxsize);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加