gpt4 book ai didi

c - 反向字符串 realloc() : invalid next size

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:48 24 4
gpt4 key购买 nike

<分区>

我创建了这个小程序来反转句子。所以给出:a b c d

它将给出:d c b a

这工作正常,直到我添加一个额外的字母。如果我尝试“a b c d e”,它将在最后一个失败并出现错误

realloc():下一个大小无效:0x0000000000602010 *

这是代码

#define MAX_TEXT 100

#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //realloc


int main(int argc, char **argv) {
char text[MAX_TEXT] = { 0 };
char *parts = NULL;

printf("Insert string: ");
fgets(text,MAX_TEXT,stdin);
sscanf(text,"%[^\n]",text); //remove the \n


char **reverse = NULL;
char **extra = NULL;
int size = 0;
int i = 0;

parts = strtok (text," ");
while (parts != NULL) {

size += ((strlen(parts)+4) * sizeof(char));
extra = realloc(reverse,size);

if (extra) {
reverse = extra;
reverse[i++] = parts;
}
else {
printf("Error allocating memory\n");
exit(1);
}

parts = strtok (NULL, " ");
}

while (--i >= 0) {
printf("%s ",reverse[i]);
}

printf("\n");
}

我对使用指针还是个新手,更不用说指向指针的指针了,所以任何帮助都会很棒。谢谢!

Ps:我尝试使用 valgrind,它只是指出 realloc 有问题,但我不明白到底是什么。

更新代码:

#define MAX_TEXT 500

#include <stdio.h>
#include <string.h> //strchr
#include <stdlib.h> //realloc


int main(int argc, char **argv) {
char text[MAX_TEXT] = { 0 };

printf("Insert string: ");
fgets(text,MAX_TEXT,stdin);
//sscanf(text,"%[^\n]",text); //remove the \n <-- Undefined behaviour :D "if copying takes place between objects that overlap, the behavior is undefined."
char *theEnter = strchr(text,'\n');
if (theEnter) {
*theEnter = 0;//remove \n
}

char **reverse = NULL;
char **extra = NULL;
char *parts = NULL;
int size = 0;
int i = 0;
size_t increse_by = sizeof(char *);

parts = strtok (text," ");
while (parts != NULL) {

size += increse_by; //pointer to pointer so increase by the size of new pointer
extra = realloc(reverse,size);

if (extra) {
reverse = extra;
reverse[i++] = parts;
}
else {
printf("Error allocating memory\n");
exit(1);
}

parts = strtok (NULL, " ");
}

while (--i >= 0) {
printf("%s ",reverse[i]);
}

printf("\n");
}

根据 Charlie Burns 的指示,我现在正在为 char * 分配内存,我还删除了 sscanf 函数并使用 strchr 删除了\n,因为正如 chux 指出的那样,我正在做的是未定义的行为。

感谢您的帮助:)

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com