问题
I have a very simple C program. In main, I have this operation:
int main(){
int theNumber = 9009;
printf("%s", (char *)theNumber);
}
And when I run it, it gives me a seg fault. Any idea why? Am I doing this wrong?
Expected Output
This code should convert theNumber
to a string and then print it. So the output would be:
9009
Actual Output
A segmentation fault.
回答1:
This is trying to print whatever is found at the address 9009
. Seeing as the operating system is not giving your program access to this address (it is likely being used for something else entirely) the operating system raises a segmentation fault. Read more here: What is a segmentation fault?
If you really just wanted to print the value of the integer then use the correct printf command:
int main(){
int theNumber = 9009;
printf("%d", theNumber);
}
Note that you don't need to introduce a string here to achieve this.
回答2:
Okay. Let's start by talking about what a string is in the C language. Fundamentally, it's a character pointer char *
to a location in memory that stores a null terminated series of characters.
An example of this would be:
char *str = malloc(3);
str[0] = 'h';
str[1] = 'i';
str[2] = '\0';
str
now contains the String "hi"
.
What does a type cast do?
The type casting that you are doing takes the integer 9009, and converts it to a char *
. Then, since you use that pointer as a string, means that you are telling the computer that at address 9009, there is a null terminated series of bytes.
That's probably not true though, and unless you are on specialized hardware, is certainly not what you want.
How do you convert an integer to a string
We have a fairly easy mechanism to convert printf-able data to strings via snprintf()
.
First we need to allocate memory for the resultant string. This is a common difference in C from other languages. In C, you are very aware of the memory requirements of your data.
char str[100];
int size_used = snprintf(str, 100, "%d", 9009);
assert(size_used < 100);
Now, if size_used >= 100
, then we have a problem. We overflowed our memory area. snprintf()
will write as many characters as it can, but not the null terminating zero in that case.
回答3:
Because that is not a casting of an int to a char. It's a casting of an int to a pointer to char. Basically, a pointer is a variable that holds a memory address. When you try to print that pointer, whose value is 9009, the function accesses the memory at that address, which probably is forbidden, and so you get the segfault.
To avoid that, you should use something like itoa function (be careful that it's not standard, so you may have to implement it yourself).
来源:https://stackoverflow.com/questions/24460649/segmentation-fault-when-casting-int-to-char-in-c