简体   繁体   中英

Segmentation fault when casting int to char in C

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.

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM