0

Here is a simple program that is a function which checks for the character 'a' within a string, then returns the character if found, and NULL if it is not found. I am not really sure if it is the function or the call of the function itself, here is the code.

#include <stdio.h>
char *find_char(char *str, char character);
int main(){
char *str;


printf("str\n");
scanf("%s", str);


printf("%c",*find_char(str,'a'));

return 0;
}


char *find_char(char *str, char character){

    char *pstr = str;

    while(*pstr!='\0' && *pstr!=character){
        pstr++;}

    if (*pstr!=character)
        return NULL;

        else
            return pstr;
    }
steakfry
  • 21
  • 4
  • 3
    you're not allocating any memory for `str`, so when you `scanf("%s", str);`, you're writing to memory you don't own. You need to `malloc` some memory for `str` first, or just use an array with automatic storage. – yano Dec 17 '18 at 02:36
  • 1
    Also, think about what happens when you `return NULL` and the attempt to dereference that pointer. – Some programmer dude Dec 17 '18 at 02:40
  • This is a problem for all stack variables. When you write `char *str;` the variable contains a garbage value - whatever was in that memory location before you declared the variable. For a pointer it MIGHT cause a segmentation fault but for other kinds of variables your result will just be wrong sometimes. Always initialize your variables before you use them. – Jerry Jeremiah Dec 17 '18 at 02:41
  • https://stackoverflow.com/questions/6793262/why-dereferencing-a-null-pointer-is-undefined-behaviour – Jerry Jeremiah Dec 17 '18 at 02:43

1 Answers1

0

Your problem basically lies in these two lines, the first and third code line of your main function:

char *str;        // Create pointer, pointing to ***arbitrary*** memory.
scanf("%s", str); // Write to that memory, undefined behaviour.

You need to create backing storage for the pointer so you have somewhere valid to write your input to.

A better idea would be to use a rock-solid input routine rather than relying on often-dodgy practices like writing to invalid memory, or allowing uncontrolled input into limited-size buffers. One such beast can be found here.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953