String array pointer segmentation fault when called multiple times in C -


i have simple program checks user argument , prints something. here is:

#include <stdio.h> #include <string.h> #include <stdlib.h>  const char * foo(char * input){     char *result = null;     strcpy(result, "{ ");     if (strcmp(input, "kittycat") == 0){         strcat(result, "jackpot!");     }     else{         strcat(result, "nothing");       }     strcat(result, " }");     return result; }  int main(int argc, char *argv[]){     printf("%s\n", foo(argv[1]));     printf("%s\n", foo(argv[1]));     printf("%s\n", foo(argv[1]));     return 0; } 

in main(), if print printf("%s\n", foo(argv[1])); once, program runs without errors. however, if print 3 times shown above, "segmentation fault: 11". ideas? know can simplify foo , avoid use of "char *result", understand what's wrong usage of "char *result".

const char * foo(char * input) {     char *result;     strcpy(result, "{ ");    // 'result' used uninitialized - undefined behavior  

result uninitialized. pay attention compiler warnings.

also, i'm assuming want checking input, not result here:

if (strcmp(result, "kittycat") == 0) { 

this version returns static strings:

const char *foo(char *input) {     if (strcmp(input, "kittycat") == 0)         return "{ jackpot! }";     return "{ nothing }"; } 

this version returns mallocd strings, need free:

#define max_foo_result    20  const char *foo(char *input) {     char *result = malloc(max_foo_result+1);     if (!result) return null;     result[0] = '\0';      strncat(result, "{ ", max_foo_result);      if (strcmp(input, "kittycat") == 0)         strncat(result, "jackpot!", max_foo_result);     else         strncat(return, "nothing", max_foo_result);      strncat(result, " }", max_foo_result);      return result; }  int main(int argc, char *argv[]){     const char* res;      if (argc < 2) return 1;      // memory leak - result of foo leaked      printf("%s\n", foo(argv[1]));           // fixed leak     res = foo(argv[1]);     if (res) {         printf("%s\n", res);         free(res);     }      return 0; } 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -