简体   繁体   中英

Segmentation fault error with pointer array in C

I am trying to test some code from "Pointers On C", the find_char function, which searches for a specified character. I added something of my own, that is, the main() function that calls the find_char and includes the initialized data to be searched(an array of pointers to char). I managed to fix all errors and warnings at compile time, but while trying to run the a.out file, I got the segmentation fault error.

I know segmentation fault is mostly concerned with array and pointers which so often happens when types are incorrectly translated. But I really can't find what is wrong with my code.

Thank you so much.

#include <stdio.h>
#define TRUE  1
#define FALSE 0

int find_char( char **strings, char value);

int main(void)
{
    int i;
    char c = 'z';
    char *pps[] = { 
            "hello there",
            "good morning",
            "how are you"
    };  
    i = find_char(pps, c); 
    printf("%d\n", i); 
    return 0;
}

int find_char (char **strings, char value)
{
    char *string;
    while (( string = *strings++) != NULL)
    {   
            while (*string != '\0')
            {   
                    if( *string++ == value )
                            return TRUE;
            }   
    }   
    return FALSE;
}

Well your problem come from your outer while loop. It loops over the strings in the array until it finds a NULL string. However, you didn't terminate the array with such string, so the loop will go on after the 3rd string and end up trying to access memory it isn't supposed to.

A solution to your problem: You can modify your function's signature by giving it a size parameter so that it becomes

int find_char(const **char strs, int size, char ch);

Then you need to include this size value in the looping process to find your stop condition.

char *s = NULL;
int i = 0;
while (i++ < size && (s = *strs++)) {
    // ...
}

The point to remember here is that, in C programming it is required to play with memory and arrays carefully. When dealing with arrays, one usually want to pass the array's size as a parameter to each processing functions.

I hope that helped.

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