2014-02-15 3 views
1

내 프로그램에서 수행하려는 작업은 한 문자열의 내용을 다른 문자열로 역순으로 복사하는 것입니다. 이 프로그램의 일부가 작동합니다.메모리를 다시 할당하면 C에서 작동하지 않습니다

그러나 사용자 입력을 제한하고 싶지 않으므로 malloc 및 realloc을 사용하고 싶습니다. 이것은 내 코드입니다.

#include <stdio.h> 
#include <stdlib.h> 
/*copy one string to another, in reverse*/ 
void copyStr(char *p, char *h){ 

    int i=0,j=0; 
    int length=0; 
    length=strlen(p); int l=length; 
    for (i=0; i<length; i++){ 
     h[i]=p[l-1]; 
     l--; 
    } 
    char *temp=&h[0]; 
    for (i=0; i<length; i++){ 
     printf("%c",temp[i]); 
    } 


} 
main(){ 
    printf("please enter a string\n"); 
    char c; int i=0; int end=10; 
    /*allocate initial memory*/ 
    char *p=(char*)malloc(sizeof(end)); char *temp=p; 
    while (c!='\n') 
    { 
     /*reallocate if needed*/ 
     if (i==(end-1)){ 
      end*=2; 
      temp = realloc(p,end*sizeof(temp)); 
      if (temp!=NULL){ 
       /*this is for myself, to see what the error was*/ 
       printf("error allocating\n"); 
       exit(1); 
      } 
      else 
       free(p); 
     } 
     c=getchar(); 
     p[i]=c; 
     i++; 
    } 

    char h [sizeof(p)]; 
    copyStr(p,h); 
} 

realloc 함수가 작동하지 않아서 도움을 요청했습니다.

입력이 매우 짧으면 (즉 3 자) 프로그램이 작동합니다. 글자가 10자를 넘으면 메모리를 재 할당하지 않습니다. 5보다 길면 역순으로 인쇄되지만 "stack smashed"라는 메시지가 나에게 전송됩니다. 감사합니다.

+0

어쩌면'온도 = (숯불 *) realloc을 (P, 최종 *의를 sizeof (온도가))'일 것이다 ...'때문에 * 온도 = (char *) realloc (p, end * sizeof (temp));'이상하게 보입니다. – francis

+0

'temp = realloc (p, end * sizeof * temp); – wildplasser

+0

모두 시도했지만 여전히 작동하지 않습니다 ... – Alan

답변

1

는 사실, 몇 가지 작은 트릭 변경이 있습니다 :

  • *temp=realloc(...temp=realloc(...
  • temp!=NULLrealloc()의 정상적인 동작이 사실이 될 것이다.
  • 나중에 사용하는 경우 다시 할당 작업 후 p을 변경하는 것을 잊지 마십시오.
  • sizeof(p) 난 나도 문자열의 끝에있는 문자 \0 추가 char h [sizeof(char)*(i+1)];
  • 로 설정되어 ... 즉, 4 또는 8이고, 포인터의 크기이다. 이는 인쇄하거나 strlen()#include string.h을 사용하려는 경우 유용합니다. 그럼 당신은 여기

printf("the result is :\n%s \n",h); 코드 간다 수 있습니다

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
/*copy one string to another, in reverse*/ 
void copyStr(char *p, char *h){ 

    int i=0,j=0; 
    int length=0; 
    length=strlen(p); int l=length; 
    for (i=0; i<length; i++){ 
     h[i]=p[l-1]; 
     l--; 
    } 
    //keep end-of-string character 
    h[length+1]='\0'; 
    /* char *temp=&h[0]; 
    for (i=0; i<length; i++){ 
     printf("%c",temp[i]); 
    }*/ 
    printf("the result is :\n%s \n",h); 



} 
main(){ 
    printf("please enter a string\n"); 
    char c; int i=0; int end=10; 
    /*allocate initial memory*/ 
    char *p=(char*)malloc(sizeof(end)); char *temp=p; 
    //signaling end of string 
    p[0]='\0'; 
    while (c!='\n' && c!=EOF) 
    { 
     /*reallocate if needed*/ 
     if (i==(end-2)){ 
      end*=2; 
      temp=(char*)realloc(p,end*sizeof(char)); 
      if (temp==NULL){ 
       /*this is for myself, to see what the error was*/ 
       printf("error allocating\n"); 
       exit(1); 
      } 
      else{ 
       p=temp; 
       printf("ok here\n"); 
      } 
     } 
     c=getchar(); 
     p[i]=c; 
     i++; 
    } 
    //signaling end of string 
    p[i+1]='\0'; 

    printf("INVERTING STRING\n"); 
    char h [sizeof(char)*(i+1)]; 
    copyStr(p,h); 

      free(p); 
} 

! 에니 프 krow OT가 smees TI

안녕,

프랜시스

+0

두 가지 사실이 있습니다. 1. 귀하의 코드 작업. 2. 어떻게 작동하는지 배워야합니다. 고맙습니다! – Alan

+1

장래에 메모리 누출을 피하기 위해'free (p)'를 끝에 추가했습니다 ... 안녕, Francis – francis

1

해당 없음 *temptemp입니다. Realloc은 포인터를 저장해야하는 메모리가 할당 된 위치의 주소를 반환합니다. 포인터가 가리키는 주소를 저장하지 않는 것은 이미

0
*temp=(char*)realloc(p,end*sizeof(temp)); 

이 포인터가 temp입니다

temp = realloc(p,end*sizeof(temp)); 

, *temp 콘텐츠를 의미 할 어떤 의미를하지 않습니다 것이다.

+0

고맙습니다, 말씀하신대로 고쳐 주셨지만 여전히 작동하지 않습니다. – Alan

+0

'temp = realloc (p, end * sizeof * temp); ' – wildplasser