Eden_Yosef
Eden_Yosef

Reputation: 45

Segmentation fault when releasing a string in C

I have a "segmentation fault" error when I try to free the allocated memory of the string pointed from "new_job->jobs_adress" . I've allocated enough memory for my string (even if I allocate far beyond from what I need, I still have this problem), But there is still this error.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct job_t {
    pid_t pid;
    time_t creation_time;
    bool stop;
    bool foreground;
    char * jobs_adress;
} Job;

int main() {

    char * jobs_adress = "string";

    /* creating an object of "Job" Type */
    printf("another try");
    Job * new_job = (Job*)malloc(sizeof(new_job));
    if(!new_job) {
        return;
    }

    /* allocating memory for a new string, and copies the old string
      into the new string*/

    int length2=strlen(jobs_adress);
    char * str2 = malloc(length2+1);
    strcpy(str2,jobs_adress);
    new_job->jobs_adress=str2;               

    new_job->pid = 1;
    new_job->creation_time = time(NULL);
    new_job->stop=false;
    new_job->foreground=true;

    free(new_job->jobs_adress);  // <=== the error is here

}

Upvotes: 0

Views: 74

Answers (1)

abelenky
abelenky

Reputation: 64700

Job * new_job = (Job*)malloc(sizeof(new_job));

On this line, sizeof(new_job) is measuring the size of variable new_job.

new_job has type Pointer, and a pointer is (typically) 4 bytes.
So you allocate 4 bytes.

You intended to allocate enough space for a Job struct.
The line should've been:

Job * new_job = (Job*)malloc(sizeof(Job));

Upvotes: 8

Related Questions