4

ユーザーが名前を入力すると配列が大きくなるので、realloc関数を使用しようとしています。5.要素を追加すると、エラーが発生します。次のようなエラーが検出されました: *glibcが検出されました./a.out:realloc():無効な次のサイズ:0x00000000017d2010**そしてコードは次のとおりです。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
  char **mtn = NULL;
  char x[30];
  int i = 0;

  while ( strcmp(gets(x), "finish") ){
    mtn = realloc( mtn, i*sizeof(char) );
   // mtn[i] = realloc( mtn[i], sizeof(x) ); // tried but didnt work
    mtn[i] = x;
    i++;
  }
  puts(mtn[1]);

  return 0;
}
4

1 に答える 1

3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char **mtn = NULL;
    char x[30];
    int i = 0;

    /* Never use gets, it's dangerous, use fgets instead */
    while (strcmp(fgets(x, sizeof(x), stdin), "finish\n")){
        /*
        your previous realloc was realloc(mtn, 0)
        and you have to take space for <char *>
        */
        mtn = realloc(mtn, (i + 1) * sizeof(char *));
        /* always check return of xalloc */
        if (mtn == NULL) {
            perror("realloc");
            exit(EXIT_FAILURE);
        }
        /* you still need space for store x */
        mtn[i] = malloc(strlen(x) + 1);
        if (mtn[i] == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(mtn[i], x); /* mtn[i] = x is not valid */
        i++;
    }
    printf("%s", mtn[1]);
    /* always free xallocs in order to prevent memory leaks */
    while (i--) free(mtn[i]);
    free(mtn);
    return 0;
}
于 2012-12-22T04:54:00.123 に答える