C - store to null pointer error, segmentation fault -


please bear code. i'm beginner in c. code below builds vigenere cipher. user inputs key argument used encrypt plaintext message. code output ciphertext.

the error receive follows. note have not studied pointers yet.

any in diagnosing error appreciated!

vigenere.c:47:13: runtime error: store null pointer of type 'char' segmentation fault 

the code

#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h>  int main(int argc, string argv[]){  // check 2 arguments if (argc != 2){      printf("missing command-line argument\n");     return 1;  }   // check character argument int i,n;  (i = 0, n = strlen(argv[1]); < n; i++){      if (!isalpha(argv[1][i])){          printf("non-character argument\n");         return 1;      }  }  // if previous 2 checks cleared, request 'plaintext' user  printf("plaintext:");  // declare plaintext, key, , ciphertext  string t = get_string();    // plaintext string u = argv[1];         // key (argument) string y = null;            // ciphertext  // encode plaintext key -> ciphertext  (i = 0, n = strlen(t); < n; i++){      if (tolower(t[i])){          y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 97) % 26) + 97;      } else {          y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 65) % 26) + 65;      }   }   printf("ciphertext: %s\n", y);  } 

you error message because variable yis null.

type string typedef (an alias in other words) char * means "pointer char" therefore y pointer char.

when doing y[i], dereference null pointer not allowed , leads error. nullrepresents non-existing memory space can not store ciphertext here !

to solve problem can declare , initialize y follows :

char *y = calloc(strlen(t) + 1, sizeof(char)); // ciphertext, ready hold data ! 

you have #include <stdlib.h>in order use calloc() function.

now, y pointer memory space large t (plaintext , cyphertext have same size) can dereference , write data !

you should learn pointers , how memory works before going further. programmer dude posted great list of books in comments of original post, take @ !


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -