[英]C struct Segmentation fault
After entering the second element, it throws me out x.输入第二个元素后,它把我抛出 x。 I know that allocating memory for each element is not appropriate, but I wanted to better detect errors.I want to save two character fields for which I do not know the size in advance.
我知道为每个元素分配 memory 是不合适的,但我想更好地检测错误。我想保存两个我事先不知道大小的字符字段。
typedef struct
{
char *m_Cislo;
char *m_Jmeno;
} TSEZNAM;
TSEZNAM * readNumbers (int *nr)
{
char *str = NULL;
size_t capacity = 0;
TSEZNAM st;
TSEZNAM *res = NULL;
*nr=0;
while ( getline(&str, &capacity, stdin) != -1 )
{
st.m_Jmeno = malloc(sizeof(char)*capacity);
st.m_Cislo = malloc(sizeof(char)*capacity);
sscanf(str,"%s %s", st.m_Cislo, st.m_Jmeno);
TSEZNAM *tmp = (TSEZNAM*) malloc ((*nr+1)*sizeof(*res));
for(int i=0; i < *nr; i++)
tmp[i] = res[i];
free(res);
res=tmp;
res[*nr]=st;
*(nr)++;
}
return res;
}
int main(void)
{
int listNr;
TSEZNAM *list = readNumbers(&listNr);
}
The parentheses in your *(nr)++;
*(nr)++;
statement actually achieve nothing (you are simply wrapping the name of the nr
variable);语句实际上什么也没做(您只是包装了
nr
变量的名称); thus, the effect of this statement is to increment the value of the pointer - which will cause problems in the second (and subsequent) loop(s), because it will then be pointing to an invalid location.因此,该语句的作用是增加指针的值——这将导致第二个(和后续)循环出现问题,因为它将指向一个无效的位置。 This is because the post-increment (
++
) operator has higher precedence than the indirection ( *
) operator.这是因为后自增 (
++
) 运算符的优先级高于间接 ( *
) 运算符。
In fact, with full warnings enabled, your compiler will likely find this problem;事实上,启用完整警告后,您的编译器很可能会发现这个问题; for example, clang-cl gives:
例如,clang-cl 给出:
warning: expression result unused [-Wunused-value]
警告:表达式结果未使用 [-Wunused-value]
To fix the problem, you need to place the dereference operator ( *
) inside the brackets, like this: (*nr)++
.要解决此问题,您需要将取消引用运算符 (
*
)放在括号内,如下所示: (*nr)++
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.