2017-01-08 24 views
0

下面的程序崩潰時,對於大n(n> 200)的分段,請您幫我解決。對於較大的值獲取分段錯誤

#include <stdio.h> 
#include <string.h> 
#include <math.h> 
#include <stdlib.h> 

struct node { 
    char name[16]; 
    char num[8]; 
}; 
int main() { 
    int n, i,j; 
    struct node *hash; 
    scanf("%d",&n); 
    hash = (struct node *) malloc(n * sizeof(struct node)); 
    for (i=0; i<n ; i++) { 
     scanf("%s %s", (hash + (i *sizeof(struct node)))->name, 
         (hash + (i *sizeof(struct node)))->num); 
    } 
for (i=0; i<n ; i++) { 
     printf("%s=%s\n",(hash + (i *sizeof(struct node)))->name, 
         (hash + (i *sizeof(struct node)))->num); 
    } 
return (0); 
} 
+1

輸入什麼字符串?任何大於15個字符或長度超過7位數字的名稱都會導致未定義的行爲,這可能會導致seg錯誤。 – StoryTeller

+3

您想了解[pointer-arithmetic](http://stackoverflow.com/documentation/c/256/operators/2205/pointer-arithmetic#t=201701081538077668512)。這個'(hash +(i * sizeof(struct node)))...'應該是'(hash + i)...'或者只是'&hash [i] ...'。 – alk

+1

另外,你的指針偏移很難閱讀(除了錯誤和超出你分配的內存)。讓編譯器處理'struct node'的大小,然後直接寫'hash [i]'。 – StoryTeller

回答

3

向指針添加整數時,編譯器會執行指針算術。所以hash + i被編譯器翻譯成類似(char*)hash + i * sizeof(struct node)的東西。以字節爲單位計算偏移量,然後以字節應用

你的代碼,因此相當於

(char*)hash + i * sizeof(struct node) * sizeof(struct node) 

這將超越數組邊界非常快,調用未定義的行爲。

隨着意見總結,要麼使用(hash + i)或更簡潔(在我看來)hash[i]

0
#include <stdio.h> 
#include <stdlib.h> 

struct node { 
    char name[16]; 
    char num[8]; 
}; 

int main(void) { 
    size_t n; 
    if (scanf("%zu", &n) != 1) { 
     return 1; 
    } 

    struct node *hash = malloc(n * sizeof *hash); 
    if (hash == NULL) { 
     return 1; 
    } 

    for (size_t i = 0; i < n; i++) { 
     if (scanf("%15s %7s", hash[i].name, hash[i].num) != 2) { 
      free(hash); 
      return 1; 
     } 
    } 

    for (size_t i = 0; i < n; i++) { 
     printf("%s %s\n", hash[i].name, hash[i].num); 
    } 

    free(hash); 
} 
+2

這並不能解釋OP爲什麼他/她的程序不起作用,因此不能幫助OP理解和學習如何進一步避免它。 –