簡體   English   中英

在C中釋放字符串時出現分段錯誤

[英]Segmentation fault when releasing a string in C

當我嘗試釋放從“ new_job-> jobs_adress”指向的字符串的分配內存時,出現“ segmentation fault”錯誤。 我已經為字符串分配了足夠的內存(即使我分配的內存遠遠超出了我的需要,我仍然有此問題),但是仍然存在此錯誤。

#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));

在這一行上, sizeof(new_job)正在測量變量new_job的大小。

new_job類型為Pointer,指針(通常)為4個字節。
因此,您分配了4個字節。

打算Job結構分配足夠的空間。
該行應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM