Chinaunix

标题: 为什么程序结束时会出现段错误? [打印本页]

作者: whizchen    时间: 2006-02-13 19:05
标题: 为什么程序结束时会出现段错误?
哪位大虾帮忙看看,为什么程序结束时会出现段错误
  1. #include <stdio.h>

  2. main(){
  3.         char *cpu_usage;
  4.         char* cpu(char *usage);

  5.         cpu(cpu_usage);
  6.        
  7.         printf ("%s\n",cpu_usage);
  8.         printf ("ok\n");
  9.        
  10. }

  11. char* cpu(char *usage)
  12. {
  13.         unsigned int total,total1,total2;

  14.         float user1,user2,nice1,nice2,system1,system2,idle1,idle2;
  15.         float user,nice,system,idle;

  16.         char cpu[100];
  17.         char text[201];

  18.         FILE *fp;

  19.         fp = fopen("/proc/stat", "r");
  20.         while (fgets(text, 200, fp))
  21.         {
  22.                 if (strstr(text, "cpu "))
  23.                 {
  24.                         printf ("%s\n",text);
  25.                         sscanf(text, "%s %f %f %f %f", cpu, &user1, &nice1, &system1, &idle1);
  26.                 }
  27.         }
  28.         fclose(fp);

  29.         total1 = (user1 + nice1 + system1 + idle1);
  30.        
  31.         sleep(1);
  32.         fp = fopen("/proc/stat", "r");
  33.         while (fgets(text, 200, fp))
  34.         {
  35.                 if (strstr(text, "cpu "))
  36.                 {
  37.                         printf ("%s\n",text);
  38.                         sscanf(text, "%s %f %f %f %f", cpu, &user2, &nice2, &system2, &idle2);
  39.                 }
  40.         }
  41.         fclose(fp);

  42.         total2 = (user2 + nice2 + system2 + idle2);               
  43.                
  44.         user = 100*(user2 - user1)/(total2 - total1);
  45.         system = 100*(system2 - system1)/(total2 - total1);
  46.         idle = 100-user-system;

  47.         sprintf(usage, "%4.2f%,%4.2f%,%4.2f%", user, system, idle);
  48.         printf ("%s\n",usage);

  49.         return usage;
  50. }
复制代码


运行结果:
  1. cpu  4490243 13506 2033119 363362296

  2. cpu  4490243 13506 2033121 363362496

  3. 0.00%,1.03%,98.97%
  4. 0.00%,1.03%,98.97%
  5. ok
  6. 段错误
复制代码

作者: ilcj    时间: 2006-02-13 19:22
没有为指针usage分配空间!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2