c - 在 C 中使用 Realloc 的字符串

标签 c arrays string realloc

<分区>

我正在尝试使用 realloc 函数使数组随着用户输入的名称而变大。当我添加 5.element 时它给我一个错误,错误如下: * glibc 检测到 ./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;
}

最佳答案

#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;
}

关于c - 在 C 中使用 Realloc 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998943/

相关文章:

c++ - 将类型定义的数组分配给另一个数组 (c++)

java - 从单个字符串按字母顺序排列列表

c - C 中函数调用指针的问题

c - 全局变量作为函数 C 中的参数

c - Linux C读取文件UNICODE格式文本(记事本Windows)

c - libusb_get_device_descriptor() 始终返回 0。如何检测故障?

Android字符串占位符不同的语言

c - 使用 pthread 让一个线程执行其他线程发送的所有磁盘写入操作?

c - 基数排序通过仅更改计数子例程的一个循环给出错误的答案

java - 如何创建(然后获取元素)列表的数组/列表?