简体   繁体   English

在C中释放字符串时出现分段错误

[英]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" . 当我尝试释放从“ new_job-> jobs_adress”指向的字符串的分配内存时,出现“ segmentation fault”错误。 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

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

On this line, sizeof(new_job) is measuring the size of variable new_job . 在这一行上, sizeof(new_job)正在测量变量new_job的大小。

new_job has type Pointer, and a pointer is (typically) 4 bytes. new_job类型为Pointer,指针(通常)为4个字节。
So you allocate 4 bytes. 因此,您分配了4个字节。

You intended to allocate enough space for a Job struct. 打算Job结构分配足够的空间。
The line should've been: 该行应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM