char上的分段错误

时间:2012-05-11 01:59:11

标签: c string segmentation-fault

运行prog.c时出现分段错误。我发现它与我的* char有关。这是代码。

prog.c中

#include <stdio.h>
#include "worker.h"
#include "manager.h"
#include "employee.h"

int main(int argc, char **argv) {
  int i;
  Worker boss = (Worker) new_Manager("Carl Cracker", 80000, 1987, 12, 15);
  return 0;       
}

worker.h

#ifndef _WORKER_H_
#define _WORKER_H_

 #define WORKER   char *name;   \
          double salary;    \
          long hireDay; \
          void (*raiseSalary)(Worker this, double byPercent);   

typedef struct Worker_struct* Worker;
struct Worker_struct {
   WORKER;
} Worker_struct;

void raiseSalary(Worker this, double byPercent);

#endif

worker.c

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

#include "worker.h"

void raiseSalary(Worker this, double byPercent) {
  Worker worker = (Worker) this; 
  printf("worker_c: raising salary\n");
  double raise = worker->salary * byPercent / 100;
  worker->salary = worker->salary + raise;
}

manager.h

#ifndef _MANAGER_H_
#define _MANAGER_H_

#include "worker.h"


typedef struct Manager_struct* Manager;
struct Manager_struct {
  WORKER;
  double bonus;
void (*setBonus)(Worker this, double b);
} Manager_struct;

Manager new_Manager(char *name, double salary, int year, int month, int day);
#endif

manager.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "manager.h"

static void setBonus(Worker this, double b) {
  Manager manager = (Manager) this; 
  manager->bonus = b;
}

Manager new_Manager (char *name, double salary, int year, int month, int day) {
  Manager manager;
  strcpy (manager->name, name);//----i think my problem is here----
 manager->salary = salary;
 manager->bonus = 0;    
 manager->setBonus = setBonus;
 manager->raiseSalary = raiseSalary;

return manager;
}

我认为我的问题出在strcpy的manager.c中。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您已在char *name宏中声明WORKER,但尚未为其分配内存。

请不要像这样在宏中定义变量;绝对没有任何好处,它会不必要地使代码复杂化。只需在Worker_struct

中直接定义它们即可