【问题标题】:Why is malloc assigning an already allocated memory position?为什么 malloc 分配已分配的内存位置?
【发布时间】:2018-10-01 19:31:16
【问题描述】:

我知道 malloc 在多次调用时应该使用未分配的内存,除非它之前已被释放。但是在这里不起作用,非常感谢您提供任何帮助。

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

struct thread_params
{
    char *str;
};

void *threadFunc(void* parameters)
{
    struct thread_params* p = (struct thread_params*) parameters;

    printf("Working with pointer %p\n", &p->str);

    return NULL;
}

int main(void)
{
    int i;
    for (i=1; i<=2; i++) {
        pthread_t tid;
        struct thread_params thread_args;
        char *a = malloc(sizeof(char));
        thread_args.str = a;
        pthread_create(&tid, NULL, &threadFunc, &thread_args);
        pthread_join(tid, NULL);
    }

    return 0;
}

这个输出

Working with pointer 0x7ffeec881b28
Working with pointer 0x7ffeec881b28

同一个指针

【问题讨论】:

  • 试试&amp;thread_args[i]怎么样
  • 伙计们,这个程序没有比赛,这就是pthread_join 的用途。我也没有看到未定义的行为(UBsan 和 TSAN 也没有),它只是在泄漏 as,但一切都应该如此。

标签: c malloc


【解决方案1】:

如果你想引用不同的thread_args,你需要一个它们的数组。此外,您很可能希望将指针打印在 str 而不是该指针的 &amp;address

只有一个thread_args,而您只是打印其中一个成员的地址(一个指针)。不是那个指针的值。

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

struct thread_params
{
    char *str;
};

void *threadFunc(void* parameters)
{
    struct thread_params* p = (struct thread_params*) parameters;

    printf("Working with pointer %p\n", p->str);

    return NULL;
}

int main(void)
{
    int i;
    for (i=1; i<=2; i++) {
        pthread_t tid;
        struct thread_params thread_args;
        char *a = malloc(sizeof(char));
        thread_args.str = a;
        pthread_create(&tid, NULL, &threadFunc, &thread_args);
        pthread_join(tid, NULL);
    }

    return 0;
}

【讨论】:

  • thread_args 需要在for 循环之外声明,否则循环重复时作用域结束。
  • thread_args 不是问题的一部分。只有打印功能中的错误。
  • 大声笑,两个正确答案都有反对票,而我部分正确的答案有赞成票。奇怪。
  • thread_args 确实变得很重要,因为它在我的实际代码中很有用,谢谢你们俩
【解决方案2】:

要打印 malloc'ed 内存的地址,请执行

  printf("Working with pointer %p\n", p->str);

您的代码不是打印 malloc() 返回的内存地址,而是打印 thread_params 结构中的 str 变量的地址。 该地址可能每次都相同,因为您的 thread_args 变量的位置在循环迭代之间可能不会改变。

请注意,如果没有您的 pthread_join() 调用,您会将指向新线程的指针传递给在循环的下一次迭代中超出范围的变量,这将导致未定义的行为,因此请注意生命周期无论你传入pthread_create

【讨论】:

    【解决方案3】:

    您没有打印malloc() 返回的地址。您正在打印&amp;p-&gt;str,这是结构成员的地址。编译器每次循环都为结构使用相同的内存,所以str成员的地址不会改变。

    &amp;p-&gt;str更改为p-&gt;str,您将打印malloc()返回的地址。

    【讨论】:

      【解决方案4】:

      不错 :-) 在您的 printf 声明中,您有 &amp;p-&gt;str --- 代替 p-&gt;str 怎么样?

      这将使您: Working with pointer 0x6020000000b0 Working with pointer 0x6020000000d0 这似乎更合理。之前,我想你得到的是结构成员在内存中的地址。

      【讨论】:

      • 它显示了来自循环的a的相同地址和来自线程函数的`p`。
      • @mayur 但是你运行的是不同的程序!
      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 2014-04-24
      • 2013-07-04
      • 2012-12-26
      • 2013-02-23
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多