[英]strcmp segmentation fault with array of structs
所以我有這段代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hw09-header.h"
struct student
{
char* name;
char* course;
};
int main(int argc, char* argv[])
{
int i = 0, init_size=10,x,z;
char *value = "go";
int key, count=0;
char* del = ","; /*Uses comma sign as delimiter*/
char *token=NULL;
char *temp_stor;
struct student *array;
struct student *temp;
if(argc != 2)
{
printf(" usage: program_name positive_integern");
printf("example: ./example-hw09 123n");
exit(1);
}
/************** begin REQUIRED **************/
/* put before logic. DO NOT PUT IN A LOOP */
key = atoi(argv[1]);
initialize(key);
/************** end REQUIRED **************/
/* example loop */
array=malloc((init_size)*sizeof(int));
while(strcmp(value, "stop") != 0)
{
value = getString();
token = strtok(value, del);
while (token !=NULL)
{
if(i%4==0)
{
init_size=init_size*2;
temp = realloc(array,init_size*sizeof(int)) ;
if(temp != NULL)
{
array = temp;
}
else
{
printf("unable to reallocaten");
exit(1);
}
}
array[i].name=malloc(sizeof(struct student)*10);
strcpy(array[i].name,token);
printf("%s %dn",array[i].name,i);
token = strtok( NULL, del );
array[i].course=malloc(sizeof(struct student)*11);
strcpy(array[i].course,token);
printf("%s n",array[i].course);
i=i+1;
token = strtok( NULL, del );
x=i;
for(x=0; x<i; x++)
{
if(strcmp(array[x].name,token)==0)
printf("Duplicate found n");
}
}
}
}
現在當我嘗試做strcmp時,它總是給我一個分段錯誤,我不知道為什么。
我不應該在這里使用鏈接列表,我認為我已經完成了所有工作,對於接下來的幾個部分我只需要比較和排序,我不斷得到分段錯誤。
而且我的數組中確實有元素,我可以將它們打印出來,只是因為某些原因不比較它們。
部分答案,指出沒有意義的事情。 您應該嘗試了解原因,以便修復它們。 但是SO並不是解釋malloc
如何工作的正確網站。
array[i].name=malloc(sizeof(struct student)*10);
strcpy(array[i].name,token);
您為10個student
結構分配空間,然后將字符串復制到它。 這是沒有意義的。 因為name
是char*
你應該有malloc(<maximum size of string with terminating 0 included>)
。
array=malloc((init_size)*sizeof(int));
然后
array[i].name= .....
您將array
分配為整數數組(由sizeof(int)
),但隨后您使用它們就像它們是結構一樣。
然后建議:每次你有strcpy(dst, src)
,用這個替換它:
snprintf(dst, <how much space is allocated at dst>, "%s", src);
這樣可以避免緩沖區溢出,它也會迫使你想到你為dst
分配了多少空間(如果你不知道,那么你需要解決和解決的第一個問題)。
因為,很明顯(也就是你說過)令牌是空的。
if(strcmp(array[x].name,token)==0)
將NULL
參數傳遞給strcmp
是違法的。
如果使用NULL作為一個參數調用字符串比較函數,則進程將獲得SIGSEGV,
因為這些函數正在取消引用NULL指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.