malloc初始化空指针

时间:2012-01-22 11:43:56

标签: 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?

3 个答案:

答案 0 :(得分:4)

仅为apple中的第一个元素分配了内存,因此只有apple[0]指向有效的struct test

apple的所有元素分配内存:

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

free()所需的类似循环。

test.stringchar*,所以指向一个字符串文字就像你做的那样很好(尽管类型应该是const char*)。如果您希望将字符串复制到test.string,则必须malloc()空格复制到free()以后。

答案 1 :(得分:2)

根据您的最终目标,有不同的方法。

如果每次运行程序时数组中的元素数量都是常量,则根本不必使用指针:

test apple[10]; // array with 10 instances of test

test[0].string = ...;
test[1].data = ...;

如果您想使用您的方法(使用指针,现在不是必需的),您必须自己malloc()每个元素(就像您使用apple[0]或malloc一样) ()整个数组:

int num = 10;
test *apple = malloc(sizeof(test) * num);

// access any element here
apple[5].string = "hello!";

free(apple);

答案 2 :(得分:1)

您只分配test一个实例,并将其分配给第一个数组元素:

apple[0] = malloc(sizeof(test));

要分配所有十个,你可以:

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