c - Segmentation fault when trying to declare an array of strings -
in program, trying copy each argv[i] keyword[i], program fails segmentation fault. doing wrong?
#include <stdio.h> #include <cs50.h> #include <ctype.h> #include <string.h> int main(int argc, string argv[]) { //prototype string keyword = ""; //int j; (int = 0, n = strlen(argv[1]); < n; i++) { keyword[i] = toupper(argv[1][i]); printf("%i-- printing letters\n", keyword[i]); } }
as others have observed, initialize variable keyword either empty string or pointer empty string literal, depending on definition of type string. either way, valid evaluate keyword[i] i equal zero; other value -- read or write -- out of bounds. furthermore, in latter (pointer string literal) case, must not attempt modify array keyword points to.
note in particular c not automatically expand strings if try access out of bounds element. instead, attempt produces "undefined behavior", , common way manifest in such cases in form of segmentation fault. can view segmentation fault system slapping down program attempting access memory not belong it.
since don't know a priori how long argument string before copy it, viable type keyword char *. use type instead of string in follows, clarity.
if indeed want make copy of argument, far easiest way via for-purpose function strdup():
char *keyword = strdup(argv[1]); that allocates enough memory copy of argument, including terminator, copies it, , returns pointer result. obligated free resulting memory via free() function when you're done it. having made copy in way, can upcase each element in place:
(int = 0, n = strlen(keyword); < n; i++) { keyword[i] = toupper(keyword[i]); printf("%c-- printing letters\n", keyword[i]); } note, way, printf() format descriptor single character %c, not %i. must use print characters as characters, rather integer values.
that's 1 of simplest ways write c code you're trying do, though there many variations. other 1 i'll offer consideration not copy argument @ all:
char *keyword = argv[1]; if initialize keyword way not allocate memory or make copy; instead, set keyword point same string argv[1] points to. can modify string in-place (though cannot lengthen it), provided not need retain original contents.
before wrap up, should observe program not check whether there argument. in event there not (i.e. argc < 2), argv[1] either contains null pointer (argc == 1) or undefined (argc == 0; you're unlikely ever run this). either way, program produces undefined behavior in case if attempts use argv[1] if pointer valid string. should test case first off, , terminate diagnostic message if no program argument available.
Comments
Post a Comment