[英]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.