1

this is my code:

void  Available_firmware_version(){
char *version = (char *) malloc(2);
strcpy(version, "");
FILE *fp;
int status = 0;
char path[PATH_MAX];
fp = popen("swift list Manto", "r");

if (fp == NULL){
    printf("Error: Popen is NULL \n");
    return;
}

while (fgets(path, PATH_MAX, fp) != NULL){
    version = (char *) realloc(version, strlen(version) + strlen(path));
    strcat(version, path);
    printf("%s\n", version);
}

status = pclose(fp);
if (status == -1) {
    printf("Error: Popen not closed (pclose)\n");
    return;
}
free(version);
}

When I execute code my program crash. Output is segmentation fault, before pclose(fp) command. When I delete realloc program run fine. Maybe I doing something wrong with realloc?

  • 4
    `strlen(version) + strlen(path) + 1` you're missing the NUL terminator your buffer is too short – Jean-François Fabre Apr 26 '17 at 10:40
  • 3
    You're missing one byte in your memory allocation for the '\0' caracter. – yoones Apr 26 '17 at 10:41
  • `version = realloc(version, strlen(version) + strlen(path) + 1);` don't cast return value of `realloc` – Jean-François Fabre Apr 26 '17 at 10:41
  • 2
    that said: you're very unlucky (or lucky, depends) to crash your program with only 1 byte too short. Those kind of errors are usually invisible or act like a time-bomb on your program. – Jean-François Fabre Apr 26 '17 at 10:42
  • @Jean-FrançoisFabre Well, the old [discussion](http://stackoverflow.com/q/605845/1312382) again - and there is the "do cast" fraction, too (I personally am part of...). I like the conclusion from this [answer](http://stackoverflow.com/a/33047365/1312382): "Although malloc without cast is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues." – Aconcagua Apr 26 '17 at 10:49
  • 1
    Never do `version = realloc(version ...)` What if realloc returns NULL? It will lead to a leak. – Ajay Brahmakshatriya Apr 26 '17 at 10:56
  • Thanks !!!!! Jean-François Fabre answer was correct – Mantas Pranckūnas Apr 26 '17 at 11:07

0 Answers0