문장을 뒤집기 위해이 작은 프로그램을 만들었습니다. 은 그래서 주어진 : 그것은 줄 것이다 A B C 형 D 리버스 문자열 realloc() : 다음 크기가 유효하지 않습니다.
: D를b를이 잘 작동 c를, 나는 여분의 편지를 추가 할 때까지. 나는 "ABCDE"하려고하면이 오류와 함께 마지막에
과 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에서 잘못된 점이 있음을 지적했지만 정확히 무엇을 이해할 수 없습니다.
업데이트 된 코드 : chux 내가 무엇을하고 있었는데, 표시된대로 지금의 char *에 대한 할당하고 찰리 화상 표시에 따라
이#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");
}
, 나는 또한, \ n을하기 때문에 제거하기 위해 sscanf에서 기능과 사용 strchr과 제거 정의되지 않은 동작.
감사합니다.
잘 작동합니다. 이 링크를 확인하십시오. http://ideone.com/ly8ws2 – Arpit
아무 의미도 없습니다. OP는 정의되지 않은 동작을 얻고 있습니다. –
OP는 char * 배열에 실제로 할당해야하는 경우 char * 및 문자열 자체에 대한 공간을 할당합니다. –