微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么将 pid 保留在 char 中,始终为 0?

如何解决为什么将 pid 保留在 char 中,始终为 0?

#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct mystruct {
  char string[3];
  char pid
};

int main(int argc,char** argv) {
  struct mystruct info;
  info.pid = fork();
  strcpy(info.string,"Son");
  if (info.pid == 0)
    printf("%s",info.string);
  else
    printf("Father");
  return 0;
}

代码打印

Son
Son

我想知道为什么。

解决方法

字符串 "Son" 由于终止空字节需要 4 个字节。但是 info.string 只有 3 个字节的空间,所以你会溢出它,导致未定义的行为。很可能空字节用 0 覆盖 info.pid,因为这可能是内存中的下一个字节。

无论如何,不​​要尝试将 fork() 的结果存储在 char 中。它返回一个 pid_t,这是您应该使用的类型。它很可能会溢出 char。如果返回的 pid 恰好是 256 的倍数,您的代码会错误地认为两个进程都是子进程。

,

这应该如你所愿,看看里面的改动struct mystruct

#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct mystruct {
  char string[4]; //<- Need 4 instead of 3 because of the terminating null byte
  pid_t pid;      //<- fork() return pid_t
};

int main(int argc,char** argv) {
  struct mystruct info;
  info.pid = fork();
  strcpy(info.string,"Son");
  if (info.pid == 0)
    printf("%s\n",info.string);
  else
    printf("Father\n");
  return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。