Ede*_*sef 0 c free segmentation-fault
当我尝试释放从"new_job-> jobs_adress"指向的字符串的已分配内存时,我出现"分段错误"错误.我已经为我的字符串分配了足够的内存(即使我分配的远远超出我的需要,我仍然有这个问题),但仍然存在这个错误.
#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
}
Run Code Online (Sandbox Code Playgroud)
Job * new_job = (Job*)malloc(sizeof(new_job));
Run Code Online (Sandbox Code Playgroud)
在这一行,sizeof(new_job)是测量变量的大小new_job.
new_job具有类型指针,指针(通常)为4个字节.
所以你分配4个字节.
您打算为Job结构分配足够的空间.
这条线应该是:
Job * new_job = (Job*)malloc(sizeof(Job));
Run Code Online (Sandbox Code Playgroud)