C struct problem
I am a C beginner, and I am curious why this gives me a Seg Fault everytime:
#include <stdio.h>
#include <stdlib.h>
struct Wrapper {
int value;
};
int main () {
struct Wrapper *test;
test->value = 5;
return 0;
}
I know I don't fully understand pointers yet, but I thought that
struct_ptr->field
is the same as
(*struct_ptr).field
so trying to make an assignment right to the field should be开发者_StackOverflow社区 ok. This works like expected:
struct Wrapper test;
test.value = 5;
but I am curious why using the pointer causes a Seg Fault.
I am on Ubuntu 9.04 (i486-linux-gnu), gcc version 4.4.1
You didn't assign the pointer to anything. It's an uninitialized pointer pointing to who knows what, so the results are undefined.
You could assign the pointer to a dynamically created instance, like this:
int main () {
struct Wrapper *test;
test = (struct Wrapper *) malloc(sizeof(struct Wrapper));
test->value = 5;
free(test);
return 0;
}
EDIT: Realized this was C, not C++. Fixed code example accordingly.
You need to create an instance of Wrapper first:
struct Wrapper *test;
test = new struct Wrapper;
test->Value = 5;
Good luck.
You are using an uninitialised pointer, hence the segfault.
Catching this kind of error is possible, if you turn on some more warnings, using -Wall
for example
You need to use -Wall in conjonction with some optimisation (-On) for the warning to appear. For instance, compiling your code with
gcc -Wall -O2 -c test.c
resulted in the following error message :
test.c: Dans la fonction «main» :
test.c:10: attention : «test» is used uninitialized in this function
While using french word, this compiler message is not an insult but a warning ;) See below for a code allocating memory for your test pointer
int main () {
struct Wrapper *test;
test = malloc(sizeof(struct Wrapper))
if(test == NULL) {
/* error handling */
}
test->value = 5;
free(test)
return 0;
}
精彩评论