C语言中使用Realloc的字符串处理

4

我正在尝试使用realloc函数来扩大数组,以便用户输入更多的名称。当我添加第五个元素时,它会给出一个错误,例如: * glibc detected ./a.out: realloc(): invalid next size: 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;
}

2
第一次通过时,您乘以1,然后践踏。不好。请使用realloc(mtn,(i + 1)* sizeof(char *))。注意也更改了sizeof(char *) - Jonathan Leffler
1
不要使用gets()。在使用gets()之前,请检查其返回值。此外,您还应该检查realloc()的返回值。puts(mtn[1])似乎也有点武断。您需要使用strcpy()来复制字符串;您需要为字符串分配空间(以及指向字符串的指针,您目前正在执行此操作)。 - Jonathan Leffler
1
帮忙一下怎么样,不要这么无礼呀@H2CO3。我已经看到你两次在恶意攻击C语言问题了,我觉得你需要阅读一下有关“过于局限”的规则:http://meta.stackexchange.com/questions/4818/what-questions-should-be-closed-with-reason-too-localized。 - Doug Molineux
1
你的意图是在 char* 指针数组中拥有 N 个相同地址的副本吗?如果不是,你必须为实际的 字符串 分配一个新的缓冲区。 - WhozCraig
1
@H2CO3:嗯,这并不是太局限了。相反,有很多单独的问题都需要解决才能修复它,我想不出一个有用的答案,它在三页以下。指针的动态数组只是第一步;然后每个字符串可能都应该是一个数组,然后你需要考虑释放内存;然后还有不安全的 gets……每个问题本身都可以成为一个好的、紧凑的问题,但是一起来看,我真的不知道“从哪里开始”,就是这样 :-) - Kerrek SB
显示剩余4条评论
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接