c - C双指针重新分配错误

标签 c pointers memory double allocation

friend 你好:)我正在练习C编程。在这个程序中,我有一个任务来制作字符串数组。我不知道这是怎么回事...大概是关于realloc的问题,我得到的错误是_crtisvalidheappointer

#define _CRT_SECURE_NO_WARNINGS
#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readString(char **s)
{
int i = 0;
char c;
printf("\nInput string:     ");
while ((c = getchar()) != '\n')
{
    i++;
    *s = realloc(*s, i*sizeof(char*));
    if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
    (*s)[i - 1] = c;
}
*s = realloc(*s, (i + 1)*sizeof(char));
if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
(*s)[i] = '\0';
}


char **load_words()
{
int cnt=0,wordcnt=0,i=0;
char **words = NULL, *input = NULL; 
readString(&input);
while (input[cnt] != '\0' && cnt < strlen(input))
{
    words = realloc(words, ++wordcnt);//errors in second repeat of the loop
    words[wordcnt] = malloc(MAX);
    i = 0;
    while (input[cnt] != ' ')
    {
        words[wordcnt][i++] = input[cnt++];
    }
    words[wordcnt][i] = '\0';
    realloc(words[wordcnt], (i + 1)*sizeof(char));
}
realloc(words, wordcnt);
free(input);
return words;
}

void main()
{
 int i;
 char **words = NULL;
 words = load_words();
 scanf("%d", &i);
}

有人可以帮助我,告诉我我在这里做错了什么吗?此函数应返回字符串数组,但数组应为双指针(字符串矩阵)

最佳答案

你需要改变

words = realloc(words, ++wordcnt);


words = realloc(words, ++wordcnt * sizeof(*words));

否则,您将无法分配足够的内存。
words[wordcnt] = malloc(MAX);

这也不正确,您应该访问words[wordcnt-1]

关于c - C双指针重新分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716580/

相关文章:

java - 如何判断 Java 对象的内存何时释放?

C 中的复数

c++ - 用于矩阵堆栈的 openGL

c - 为什么同一个地址返回不同的值?

c - 读取/写入内存中的位

python - 将压缩文件提取到内存?

c - atmega16 单端口检查 while() 循环或 if()

c - 为什么我用 C 编写的以下 getString() 函数不起作用?

c# - 不能对 C# 中的变量使用关键字 'fixed'

C 从字符指针初始化字符数组