2012-11-21 3 views
1

프로그램에 문제가 있습니다. 메신저는 간단한 알파 화 프로 그램을 더미 alfabeth와 함께 만들지 만 char 배열에 액세스하려고하면 위치에 액세스 할 수 없습니다. 어떻게됩니까? 만약 int_type 대신에 size_t 타입과 관련이 있다면 나는 모른다. 당신은으로 mess를 선언하는왜 EXC_BAD_ACCESS가 메모리에 액세스 할 수 없습니까?

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <time.h> 
#include <ctype.h> 

static char * createAlfa(void); 
char * codify(char *mess, char *alfa); 

int 
main(void) 
{ 
    char *alfa=createAlfa(); 
    printf("write your mess to codify: \n"); 
    char mess[]=""; 
    scanf("%s", mess); 
    char *code=codify(mess, alfa); 
    printf("your codified message is: %s\n", code); 
    return 0; 
} 

static char * 
createAlfa(void) 
{ 
    char *codealfa=malloc(sizeof(char)*27); 
    srand((unsigned int)time(NULL)); 
    int i, ran; 
    for(i=0; i<26; i++) 
    { 
     codealfa[i]='A'+i; 
     if((ran=rand()%26)<i) 
     { 
      codealfa[i]=codealfa[ran]; 
      codealfa[ran]='A'+i; 
     } 
    } 
    codealfa[26]=0; 
    return codealfa; 
} 

char * 
codify(char *mess, char *alfa) 
{ 
    size_t len=strlen(mess); 
    char *code=malloc(sizeof(char)*len); 
    int i; 
    for(i=0; i<len; i++) 
    { 
     int pos=(int)(toupper(mess[i])-'A'); //pos is behaving correctly, first loop is 
               //it is 15 when i write "potato" 
     code[i]=alfa[pos];  //EXC_BAD_ACCESS, Could not access memory 
    } 
    code[i]=0; 
    return code; 
} 
+0

오류가 발생하면 i 및 pos를 작성 했습니까? –

+0

힌트 : 루프가 종료 될 때'i'의 값은 얼마입니까? 이것이'malloc'으로 만든 배열 범위 내에 있습니까? –

+0

다음 위치에서 하나씩 오류가 있습니다 :'size_t len ​​= strlen (mess); char * code = malloc (sizeof (char) * len);'codify()'에 있습니다. null에 충분한 공간을 할당하려면 1을 더해야합니다. 경고 : 나는 '감자'를 입력하고 'codified'출력 POTATO를 한 번 받았다. 그것은 아주 좋은 암호화가 아닙니다. –

답변

3

: 1 동일한 크기를 만드는

char mess[]=""; 

는 NUL 문자를 개최합니다. 당신이 그 배열에 입력을 스캔하는 다음 : 충분한 공간이 아니므로

scanf("%s", mess); 

는 작동하지 않습니다.

이 문제를 해결하려면 정확한 크기 ()를 저장해야합니다. 저장하려는 문자의 최대 길이보다 하나가 길어야합니다.

+2

쥐, 나를 이길 때 –

+0

+1하지만 이것은 유일한 버그가 아닙니다 ... –

3

나는 문제로 스캔 할 문자열에 할당 전혀 기억이 없습니다

char mess[]=""; 

것을 믿는다.

char mess[MAX_LENGTH]; 
mess[0] = 0; 
또한

내가 맥 OS X에 valgrind 아래의 코드를 실행하면 scanf와 당신이 입력의 길이를 제한하지 않는 사용으로, How to prevent scanf causing a buffer overflow in C?

3

표시된다는 점에 유의로 교체

$ valgrind excbadacc 
==80786== Memcheck, a memory error detector 
==80786== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. 
==80786== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info 
==80786== Command: excbadacc 
==80786== 
write your mess to codify: 
absintheabelones 
==80786== Invalid write of size 1 
==80786== at 0x100000D1B: codify (excbadacc.c:53) 
==80786== Address 0x100007210 is 0 bytes after a block of size 16 alloc'd 
==80786== at 0xB823: malloc (vg_replace_malloc.c:266) 
==80786== by 0x100000CC5: codify (excbadacc.c:45) 
==80786== 
==80786== Invalid read of size 1 
==80786== at 0xC894: strlen (mc_replace_strmem.c:398) 
==80786== by 0x1748C2: __vfprintf (in /usr/lib/system/libsystem_c.dylib) 
==80786== by 0x17318D: vfprintf_l (in /usr/lib/system/libsystem_c.dylib) 
==80786== by 0x17C2CF: printf (in /usr/lib/system/libsystem_c.dylib) 
==80786== by 0x100000DFA: main (excbadacc.c:18) 
==80786== Address 0x100007210 is 0 bytes after a block of size 16 alloc'd 
==80786== at 0xB823: malloc (vg_replace_malloc.c:266) 
==80786== by 0x100000CC5: codify (excbadacc.c:45) 
==80786== 
your codified message is: AQBRSKHDAQDPZSDB 
==80786== 
==80786== HEAP SUMMARY: 
==80786==  in use at exit: 10,330 bytes in 36 blocks 
==80786== total heap usage: 36 allocs, 0 frees, 10,330 bytes allocated 
==80786== 
==80786== LEAK SUMMARY: 
==80786== definitely lost: 43 bytes in 2 blocks 
==80786== indirectly lost: 0 bytes in 0 blocks 
==80786==  possibly lost: 0 bytes in 0 blocks 
==80786== still reachable: 10,287 bytes in 34 blocks 
==80786==   suppressed: 0 bytes in 0 blocks 
==80786== Rerun with --leak-check=full to see details of leaked memory 
==80786== 
==80786== For counts of detected and suppressed errors, rerun with: -v 
==80786== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 1 from 1) 
$ 

하나의 문제는 당신이에 codify()에 off-by-one 오류를 가지고있다 : I 출력을 얻을

size_t len=strlen(mess); 
char *code=malloc(sizeof(char)*len); 

널 (null)에 충분한 공간을 할당하려면 1을 더해야합니다.

경고 : 한 번 실행하면 '감자'가 입력되고 '목록 화 된'결과가 표시됩니다. 그것은 아주 좋은 암호화가 아닙니다.

+0

그리고 나는 또한 '엉망'의 크기에 문제가 있다는 것을 알고 있습니다. 'valgrind'가 당신을 도울 수있는 것에는 한계가 있습니다. –

+0

함께 해결할 수 있습니다 :-) –

+0

@JonathanLeffler 제가 문제를 이미 해결했지만 어쨌든 입력에 감사 드리고 싶습니다만 투표 할 수있었습니다. 아직 valgrind를 배웠지 만 C에서 더 많은 프로그램을 배웠습니다. 더 중요한 것은 툴을 아는 것 같다. – patriques

관련 문제