z.rubi
z.rubi

Reputation: 327

Segmentation fault of small code

I am trying to test something and I made a small test file to do so. The code is:

void main(){
    int i = 0;
    char array1 [3];
    array1[0] = 'a';
    array1[1] = 'b';
    array1[2] = 'c';

    printf("%s", array1[i+1]);
    printf("%d", i);
}

I receive a segmentation error when I compile and try to run. Please let me know what my issue is.

Upvotes: 1

Views: 160

Answers (4)

CiaPan
CiaPan

Reputation: 9570

When printf sees a "%s" specifier in the formatting string, it expects a char* as the corresponding argument, but you passed a char value of the array1[i+1] expression. That char got promoted to int but that is still incompatible with char *, And even if it was it has no chance to be a valid pointer to any meaningful character string...

Upvotes: 1

tadman
tadman

Reputation: 211680

Strings need to have a NUL terminator, and you don't have one, nor is there room for one.

The solution is to add one more character:

char array1[4];
// ...
array1[3] = 0;

Also you're asking to print a string but supplying a character instead. You need to supply the whole buffer:

printf("%s", array1);

Then you're fine.

Spend the time to learn about how C strings work, in particular about the requirement for the terminator, as buffer overflow bugs are no joke.

Upvotes: 2

Roflcopter4
Roflcopter4

Reputation: 709

I suggest you get yourself a good book/video series on C. It's not a language that's fun to pick up out of the blue.

Regardless, your problem here is that you haven't formed a correct string. In C, a string is a pointer to the start of a contiguous region of memory that happens to be filled with characters. There is no data whatsoever stored about it's size or any other characteristics. Only where it starts and what it is. Therefore you must provide information as to when the string ends explicitly. This is done by having the very last character in a string be set to the so called null character (in C represented by the escape sequence '\0'.

This implies that any string must be one character longer than the content you want it to hold. You should also never be setting up a string manually like this. Use a library function like strlcpy to do it. It will automatically add in a null character, even if your array is too small (by truncating the string). Alternatively you can statically create a literal string like this:

char array[] = "abc";

It will automatically be null terminated and be of size 4.

Upvotes: 2

Achal
Achal

Reputation: 11921

Please let me know what my issue is. ? firstly char array1[3]; is not null terminated as there is no enough space to put '\0' at the end of array1. To avoid this undefined behavior increase the size of array1.

Secondly, array1[i+1] is a single char not string, so use %c instead of %s as

printf("%c", array1[i+1]);

Upvotes: 2

Related Questions