-4

Im a beginner and at school we have task to split a char array by using pointer. I want to split the name and the birthday (delimiter = '.'). My solution works perfect for the name but doing it for the birthday i get a segmentation fault.

int main(int argc, char *argv[])
{
    char *fullname;
    char *name;
    char *lastname;
    char *birthday;
    char *day;
    fullname = argv[1];
    birthday = argv[2];
    int i = 0;
    int y = 0;
    int z = 0;

    while(fullname[i] != '.'){
        char x = fullname[i];
        name[i] = x;
        fullname[i] = ' ';
        i++;
    }
    i++;

    while(fullname[i] != '\0'){
        char x = fullname[i];
        lastname[y] = x;
        fullname[i] = ' ';
        i++;
        y++;
     }

    while(birthday[z] != '.'){
         char b = birthday[z];  
         day[z] = b;
         z++;
    }
}

Input in commandline (./a is the exe file on cygwin):

./a mister.gold 11.05.2005

Output:

segmentation fault

When i launch the code without the last loop my output is:

mister
gold
dbush
  • 205,898
  • 23
  • 218
  • 273
skillstar
  • 1
  • 4
  • 1
    `name`, `lastname` and friends are not initialized to point to any valid memory. – Eugene Sh. Feb 14 '19 at 20:40
  • You can't use an uninitialized `char*` pointer. – tadman Feb 14 '19 at 20:45
  • @EugeneSh. thanks for the reply , but why does it work when i remove the last loop? – skillstar Feb 14 '19 at 20:45
  • 1
    It doesn't. It's *undefined behavior*. – Eugene Sh. Feb 14 '19 at 20:46
  • 1
    You should check that `argc == 3`, if not, for example, print an error and `return EXIT_FAILURE` (defined in `stdlib.h`) or in general, non-zero. Also, you might check that `'.'` and `'\0'` are not encountered. See https://stackoverflow.com/a/963777/2472827. – Neil Feb 14 '19 at 20:46
  • If you compiled with warnings turned on, the compiler would let you know that name, lastname and day are all used without being initialized. – bruceg Feb 14 '19 at 22:13

1 Answers1

0
char *name ;
char *lastname;

Two char array pointer , but what do they point two? nothing so you are basically trying to access a memory you don't own to allocate memory for them you should do :

 // assuming the maximum size if 512 for example or you can give it any size you think is enough
 char *name =malloc(512);
 char *lastname=malloc(512);

now they point to something you can access & modify

after you are done using them you should deallocate the dynamic allocated memory like this

free(lastname); 
free(name); 
Spinkoo
  • 2,080
  • 1
  • 7
  • 23