2013-06-03 3 views
1

나는이 버그에 잠시 고생하고 있으며 무엇이 잘못되었는지 알 수 없습니다. 나는 때문에파일을 열면 sYSMALLOc 어설 션 오류가 발생합니다.

//the code for the function that is being called 
//charset is a const char[] consisting of 91 characters 
//charset_size is 91 
void set_sequence(char keyword[], int keyword_size){ 

    sequence = malloc(keyword_size); 

    int i = 0, j = 0; 

    for(i = 0; i < keyword_size; i++){ 

     for(j = 0; j < charset_size; j++){ 

      if(keyword[i] == charset[j]){ 

       sequence[i] = j; 

      } 

     } 

    } 

    sequence_size = keyword_size; 

} 

//the function call in main 
set_sequence("foo bar\n", 8); 

//there's supposed to be stuff done here with sequence that I haven't implemented yet 
free(sequence); //sequence is a global variable that I use the function to set 

FILE* dest = fopen("cipher", "w"); 

나는 그것이있을 때 파일의 비트, 나는 어설 션 오류를 얻을 수 있기 때문에,하지만이 주석 때 코드가 절대적으로 잘 실행 포함 된 이유는 (내가 그 줄 끝에서 아무것도 : 여기 코드는 문제를 찾아내는 것을 시도 함).

valgrind의 memcheck valgrind --tool=memcheck ../bin/cipher을 통해 코드를 실행하여 문제가 무엇인지 확인했지만 이해할 수 없습니다. 출력은 다음과 같습니다.

==10608== Memcheck, a memory error detector 
==10608== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. 
==10608== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info 
==10608== Command: ../bin/cipher -e testfile 
Program running in encrypt mode 
Open source file: success 
Allocate memory for raw_input: success 
Read source file: success 
Allocate memory for input: success 
input set-> freeing raw_input 
==10608== Invalid write of size 4 
==10608== at 0x80486DC: set_sequence (in /home/hugo/Programming/C++/Cipher 
==10608== by 0x8048A86: main (in /home/hugo/Programming/C++/Cipher/bin/cipher) 
==10608== Address 0x41f6688 is 0 bytes inside a block of size 8 alloc'd 
==10608== at 0x402BB7A: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==10608== by 0x804868C: set_sequence (in /home/hugo/Programming/C++/Cipher/bin/cipher 
==10608== by 0x8048A86: main (in /home/hugo/Programming/C++/Cipher/bin/cipher) 
==10608== 
==10608== HEAP SUMMARY: 
==10608==  in use at exit: 704 bytes in 2 blocks 
==10608== total heap usage: 6 allocs, 4 frees, 1,793 bytes allocated 
==10608== 
==10608== LEAK SUMMARY: 
==10608== definitely lost: 0 bytes in 0 blocks 
==10608== indirectly lost: 0 bytes in 0 blocks 
==10608==  possibly lost: 0 bytes in 0 blocks 
==10608== still reachable: 704 bytes in 2 blocks 
==10608==   suppressed: 0 bytes in 0 blocks 
==10608== Rerun with --leak-check=full to see details of leaked memory 
==10608== 
==10608== For counts of detected and suppressed errors, rerun with: -v 
==10608== ERROR SUMMARY: 2 errors from 1 contexts (suppressed: 0 from 0) 

답변

3

시퀀스 선언은 제공하지 않습니다. char 배열인가 int 배열인가? int 배열 인 경우 malloc이 잘못되어 할당 할 필요가 있습니다 keyword_size * sizeof(int) 바이트

+0

죄송합니다. 답변을 얻으려면 시간이 좀 걸립니다. 나는 정말로 바빴다. 솔루션이 효과적이었습니다. 나는'char'가 1 바이트이고'int'가 4 바이트 인 것을 완전히 잊어 버렸습니다. 그래서 그것은 나쁜 연습 이었지만 물론'int'에 대해서도 똑같이 시도 할 때까지 눈치 채지 못했습니다. – Hugo

관련 문제