2013-07-11 6 views
1

Когда я запускаю свою программу, я получаю сообщение об ошибке «Ошибка сегментации».Ошибка сегментации в C

Я хочу знать, если есть способ, чтобы точно знать инструкции (строки кода), что привело к аварии системы Сегментация сообщение об ошибке»

код ===>

#include "GeoIP.h" 

int main() 
{ 
    FILE *f; 
    char ipAddress[30]; 
    char expectedCountry[3]; 
    char expectedCountry3[4]; 
    const char *returnedCountry; 
    GeoIP *gi; 
    int failed = 0; 
    int test_num = 1; 

    int i; 
    for (i = 0; i < 2; ++i) { 
     if (0 == i) { 
      /* Read from filesystem, check for updated file */ 
      gi = GeoIP_open("/usr/share/GeoIP/GeoIP.dat", 
          GEOIP_STANDARD | GEOIP_CHECK_CACHE); 
     } else { 
      /* Read from memory, faster but takes up more memory */ 
      gi = GeoIP_open("/usr/share/GeoIP/GeoIP.dat", GEOIP_MEMORY_CACHE); 
     } 

     if (gi == NULL) { 
      fprintf(stderr, "Error opening database\n"); 
      exit(1); 
     } 

     /* make sure GeoIP deals with invalid query gracefully */ 
     returnedCountry = GeoIP_country_code_by_addr(gi, NULL); 
     if (returnedCountry != NULL) { 
      fprintf(stderr, 
        "Invalid Query test failed, got non NULL, expected NULL\n"); 
      failed = 1; 
     } 

     returnedCountry = GeoIP_country_code_by_name(gi, NULL); 
     if (returnedCountry != NULL) { 
      fprintf(stderr, 
        "Invalid Query test failed, got non NULL, expected NULL\n"); 
      failed = 1; 
     } 

     f = fopen("/home/aa/test/country_test.txt", "r"); 

     while (fscanf(f, "%s%s%s", ipAddress, expectedCountry, expectedCountry3) 
       != EOF) { 
      returnedCountry = GeoIP_country_code_by_addr(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry) != 0) { 
       fprintf(stderr, 
         "Test addr %d for %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      returnedCountry = GeoIP_country_code_by_name(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry) != 0) { 
       fprintf(stderr, 
         "Test name %d for %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      returnedCountry = GeoIP_country_code3_by_addr(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry3) != 0) { 
       fprintf(stderr, 
         "Test addr %d for %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      returnedCountry = GeoIP_country_code3_by_name(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry3) != 0) { 
       fprintf(stderr, 
         "Test name %d for %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      test_num++; 
     } 
     fclose(f); 

     f = fopen("/home/aa/test/country_test2.txt", "r"); 
     while (fscanf(f, "%s%s", ipAddress, expectedCountry) != EOF) { 
      returnedCountry = GeoIP_country_code_by_addr(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry) != 0) { 
       fprintf(stderr, "Test addr %d %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      test_num++; 
     } 
     fclose(f); 

     f = fopen("/home/aa/test/country_test_name.txt", "r"); 
     while (fscanf(f, "%s%s", ipAddress, expectedCountry) != EOF) { 
      returnedCountry = GeoIP_country_code_by_name(gi, ipAddress); 
      if (returnedCountry == NULL 
       || strcmp(returnedCountry, expectedCountry) != 0) { 
       fprintf(stderr, "Test addr %d %s failed, got %s, expected %s\n", 
         test_num, ipAddress, returnedCountry, expectedCountry); 
       failed = 1; 
      } 
      test_num++; 
     } 

     fclose(f); 
     GeoIP_delete(gi); 
    } 
    return failed; 
} 

благодаря

+3

Для этого используйте [Valgrind] (http://en.wikipedia.org/wiki/Valgrind). –

+3

Вы пытались запустить вашу программу через отладчик, такой как gdb? – Hasturkun

+2

Конечно, скомпилируйте с -g, затем запустите с помощью отладчика ('gdb myprogram') –

ответ

8

Как заявили многие люди: используйте отладчик или инструмент, например valgrind.

Однако это может определенно быть источником проблем (я раздел неинтересные детали):

if (returnedCountry == NULL || ...) { 
    fprintf(stderr, ".. %s ..\n", returnedCountry...); 
    ... 
} 

Есть несколько примеров, как это. У вас также есть fopen звонки, где вы не проверяете возвращаемое значение. Всегда сделайте это.

+0

+1 Nice catch Jite –

+0

Во-вторых, что. У меня были ошибки сегментации от printf и co. раньше, из-за слабых NULL проверок. Однако, если блок проверяет NULL, тогда пытается его распечатать? – Craig

2

добавить -g в командную строку компиляции, а затем вы можете использовать gdb./a.out или valgrind ./a.out

(здесь ./a.out - ваше название вашей программы)

+2

'a.out' - это название программы –

Смежные вопросы