简体   繁体   中英

Printing char array in C causes segmentation fault

I did a lot of searching around for this, couldn't find any question with the same exact issue.

Here is my code:

void fun(char* name){
    printf("%s",name);
}

char name[6];
sscanf(input,"RECTANGLE_SEARCH(%6[A-Za-z0-9])",name)
printf("%s",name);
fun(name);

The name is grabbed from scanf , and it printed out fine at first. Then when fun is called, there is a segmentation fault when it tries to print out name. Why is this?

After looking in my scrying-glass, I have it:

Your scanf did overflow the buffer (more than 6 byte including terminator read), with ill-effect slightly delayed due to circumstance:

Nobody else relied on or re-used the memory corrupted at first, thus the first printf seems to work.

Somewhere after the first and before the second call to printf the space you overwrote got re-used, so the string you read was no longer terminated before encountering not allocated pages.
Thus, a segmentation-fault at last.

Of course, your program was toast the moment it overflowed the buffer, not later when it finally crashed.
Morale: Never write to memory you have not dedicated for that.

Looking at your edit, the format %6[A-Za-z0-9] tries to read up to 6 characters exclusive the terminator, not inclusive!

Since you're reading 6 characters, you have to declare name to be 7 characters, so there's room for the terminating null character:

char name[7];

Otherwise, you'll get a buffer overflow, and the consequences are undefined. Once you have undefined consequences, anything can happen, including 2 successful calls to printf() followed by a segfault when you call another function.

Are you sure that name is zero byte terminated? scanf can overflow your buffer depending on how you are calling it.

If that happens then printf will read beyond the end of the array resulting in undefined behavior and probably a segmentation fault.

You're probably walking off the end of the array with your printf statement. Printf uses the terminating null character '\\0' to know where the end of the string is. Try allocating your array like this:

char name[6] = {'\0'};

This will allocate your array with every element initially set to the '\\0' character, which means that as long as you don't overwrite the entire array with your scanf, printf will terminate before walking off the end.

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