释放对象的问题

时间:2012-07-14 16:13:59

标签: c malloc

我目前正在尝试学习C ++的C方面。

我为malloc的char数组尝试256一块内存,然后我为它分配了一个char* "Hello World!"但是当我来释放该对象时,我得到一个错误。< / p>

任何人都可以向我解释错误。

#include <exception>
#include <stdexcept>
#include <iostream>

int main()
{
    void* charVoidPointer = malloc( sizeof(char) * 256 ) ;
    charVoidPointer = "Hello World";

    std::cout << (char *)charVoidPointer;
    free (charVoidPointer);
}

4 个答案:

答案 0 :(得分:2)

void* charVoidPointer = malloc( sizeof(char) * 256 ) ;

现在charVoidPointer(顺便说一句奇怪的名字 - 如果你想要字符,使用char *并将从malloc返回的指针强制转换为256个字符的块)。这个块是未初始化的,因此几乎唯一有效的事情就是将它们全部设置为某个值,或者复制一些内容。

charVoidPointer = "Hello World";

现在charVoidPointer在<静态分配的字符数组中指向而不是,并且您丢失了malloc返回的地址。没有办法让它回来,所以这是资源泄漏。


您的代码应该类似于:

char *charPointer = (char *)malloc(256);
strcpy(charPointer, "Hello World");

字符数组复制到已分配的块中。或者,更简洁,只是

char *charPointer = strdup("Hello World");

将分配一个正确大小的块复制该字符串。您仍然使用free释放该块。

答案 1 :(得分:2)

“Hello World”由编译器静态分配。它是该计划的一部分,存在于该计划可以解决的某个地方;称之为地址12。

charVoidPointer最初指向malloc为你分配的一些地方;称之为地址98.

charVoidPointer =“Hello ...”导致charVoidPointer指向程序中的数据;地址12.您忘记了以前包含在charVoidPointer中的地址98。

你无法释放没有被malloc分配的内存。

更真实地说明我的意思:

void* charVoidPointer = malloc(sizeof(char) * 256);
printf("the address of the memory allocated for us: %p\n", charVoidPointer);
charVoidPointer = "Hello World";
printf("no longer the address allocated for us; free will fail: %p\n",
       charVoidPointer);

你的意思是:

strcpy(charVoidPointer, "Hello World");

编辑:寻址其他类型的内存的示例

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

int main()
{
  // an array of 10 int
  int *p = (int*)malloc(sizeof(int) * 10);

  // setting element 0 using memcpy (works for everything)
  int src = 2;
  memcpy(p+0, &src, sizeof(int));

  // setting element 1 using array subscripts.  correctly adjusts for
  // size of element BECAUSE p is an int*.  We would have to consider
  // the size of the underlying data if it were a void*.
  p[1] = 3;

  // again, the +1 math works because we've given the compiler 
  // information about the underlying type.  void* wouldn't have
  // the correct information and the p+1 wouldn't yield the result
  // you expect.
  printf("%d, %d\n", p[0], *(p+1));

  free (p);
}

实验;将类型从int更改为long,或double或某种复杂类型。

答案 2 :(得分:1)

使用strcpy(charVoidPointer, "Hello World");,因为在您的示例中,您重新指定指针。

答案 3 :(得分:1)

您将指针指向字符串文字“Hello World”的地址,因此您使用malloc的内存块被泄露。

你应该使用

strcpy(charVoidPointer, "Hello World");

而不是赋值运算符。

更好的方法是使用strncpy(charVoidPointer, "Hello World", 255);来避免溢出你分配的数组。