0

I'd like to get your opinion on this. I'm writing a program. During some fixing up and testing, I realized I'm forgetting to free a piece of memory I'm using. So I did, but the problem is that it now throws a SEGFAULT (but it works fine w/o the free).

  1. allocating and assigning value
        char* device = (char*) malloc(10 * sizeof(char));
        if (device == NULL){
            printf("[-] Bad pointer to devicePath. exiting..\n");
            exit(EXIT_FAILURE);
        }
    
        device = "nvme";
  1. pass onto function (which forks and exec)
        searchPathForDisk(device, devicePath);
  1. trying to set free
        free(device);     //causes SEG FAULT - why?

I thought it had something to do with the exec not finishing executing before I'm calling free, but that's not the case. Any ideas? Is it something related to exec?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Why are you mallocing when you immediately assign a string literal to `device`? – SuperStormer Feb 13 '22 at 23:40
  • On another couple of notes: 1) `sizeof(char)` is specified to *always* be equal to `1`, no matter the actual bit-width of `char`; And 2) In C you [shouldn't really cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Feb 13 '22 at 23:53
  • 1
    You basically have `device = malloc(...);` followed by `device = "nvme";`. What do you think happens with the second assignment? Where will the pointer `device` be pointing? If you want to copy a string you should use `strcpy`. – Some programmer dude Feb 13 '22 at 23:54
  • Why allocate 10 bytes to hold a 5-byte string? – Jonathan Leffler Feb 14 '22 at 00:02
  • 1
    If you must allocate dynamically, for whatever reason, use `char *device = strdup("name");` – Cheatah Feb 14 '22 at 00:35
  • sizeof(char) - just common pratice. and I'm assigning string literal to device just for the local testing porposes. it will obviously will not be the case once everything is set. – user18186432 Feb 14 '22 at 06:23

0 Answers0