c - Malloc 初始化空指针

标签 c malloc

您好,我遇到了这种情况。我正在使用 malloc 给我一个包含 10 个指针的数组。当我在 gdb 中看到测试指针时,其中一个(第三个)指向 0x0。有时在使用 apple[2]->string = "hello"时代码会出现段错误。为什么 malloc 这样做?预先感谢您的帮助。

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


int
main(void)
 {
  typedef struct test
    {
      char *string;
      int data;
    } test;

   test *apple[10];  // Declare an array of 10 test pointers. This line results in one of  the  pointers having a null value.
   apple[0] = malloc(sizeof(test));
   apple[0]->string = "hello";

   printf("The string is %s\n",apple[0]->string);
   printf("Size of apple[0]->data is %d\n",sizeof(apple[0]->data));
   printf("Size of tester is %d\n",sizeof(test));
   free(apple[0]);
   return 0;

 }

我想看看指针数组是如何工作的。我不打算使用所有 10 个指针。那么我是否只需要 malloc 我需要的东西?第三个指针是0x0是巧合吗?

最佳答案

内存只分配给 apple 中的第一个元素,所以只有 apple[0] 指向有效的 struct test

apple的所有元素分配内存:

for (int i = 0; i < sizeof(apple) / sizeof(test*); i++)
{
    apple[i] = malloc(sizeof(test));
}

free() 需要类似的循环。

test.string 是一个 char*,所以像您所做的那样指向一个字符串字面值是没问题的(虽然类型应该是 const char*)。如果您希望将字符串复制到 test.string,那么您必须在 malloc() 空间中复制并稍后使用 free()

关于c - Malloc 初始化空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960801/

相关文章:

c - 在运行时模拟命令行参数

C StdLib malloc 来自 (N)ASM

c - 用新字符串替换堆上的字符串

c - malloc时指针之间的区别

c - 在结构体中设置和分配指向结构体的指针

C 程序返回意外数字

c - 在 C 中打印数组时的奇怪行为?

c - memset 如何提供比 bzero 或 explicit_bzero 更高的安全性?

c - 通过充满单词的数组(从文件中检索)来操作文件中的单词

c - 函数结束后如何 "free"变量?