简体   繁体   中英

Segmentation fault with sizeof() on a small array ( C )

I'm having this weird issue. I've looked on other Stack Overflow posts, but they're dealing with large arrays that wouldn't affect anything with my code. They've recommended malloc() but it would be useless on something as small as this.

I'm practicing with C, and a simple thing like this:

int main()
{
    char* things[] = {"test1\n", "test2\n", "test3\n"};

    for (long unsigned int i = 0; i < sizeof(things) - 1; i++)
    {
        printf(things[i]);
    }
    
    return 0;
}

Gives a segmentation fault. It actually does end up printing test1, test2, test3, though. After it's done with that it gives a segmentation fault. What am I doing wrong?

The actual value of sizeof(things) will surprise you. Find it out.
As user stark explains:

sizeof is the total size in bytes of things, which is likely 3*8 or 24.

To be more explicit, it it not the number of characters in your quasi-strings, it is the size of pointers in your environment times 3.

So the solution is to divide the total by the size of one:

sizeof(things)/sizeof(things[0]) .

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