困惑于内存分配 [英] Confused in memory allocation

查看:59
本文介绍了困惑于内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。你能告诉我为什么这段代码片段不起作用:(简而言之,我声明了一个char *数组,并使用一个函数来获取这些字符串的值(char *),使用动态分配)

展开 | 选择 | Wrap | 行号

解决方案


大家好。你能不能告诉我为什么这段代码片段不起作用:(简而言之,我声明了一个char *数组,并使用一个函数来获取这些字符串的值(char *),使用动态分配)

展开 | 选择 | Wrap | 行号


忽略你已声明main而返回类型为int的事实(这本身就调用了未定义的行为)


你通过了nhap一个指向char(char *)的指针,然后你为它分配内存,C(和这个例子中的C ++)传递值,所以你传入a [i]的值,当在nhap中分配内存的值时main中的[i]保持不变,所以当你尝试在main中释放它时,你释放一个随机(和无效)指针。


这就是你的程序失败的原因主要(其中已分配内存的地址丢失)并且当free语句为nhap时有效。


如果要返回已分配指针的值,则将其作为返回值返回函数的值或声明nhap作为获取char **并将指针传递给指向函数的指针。

在一般情况下,类型T返回类型为T的值通过参数的函数然后代码必须具有结构

展开 | 选择 | Wrap | 行号


令人惊讶的是,程序当我编译并测试它时,m会产生错误!!

错误信息如下(我正在使用MSVC ++ 6.0):

调试断言失败!

程序...... exe

文件dbgheap.c

表达式CrtIsValidHeapPointer(pUserData)

按Abort或Retry或者忽略..

堆的东西??

P / S:另一个问题,如果我使用new和delete,我该怎么写?删除[i]或删除[] a [i] ??不要生气,因为我对使用指针很困惑:书籍说当删除删除分配的mem的BLOCK时,我必须使用delete [ ] ..!

Hi everybody.Could you tell me why this code fragment won''t work:(In brief, I declare an array of char *,and use a function to get value for these strings(char *)using dynamic allocation)

Expand|Select|Wrap|Line Numbers

解决方案

Hi everybody.Could you tell me why this code fragment won''t work:(In brief, I declare an array of char *,and use a function to get value for these strings(char *)using dynamic allocation)

Expand|Select|Wrap|Line Numbers


Ignoring the fact that you have declared main with out a return type of int (which in itself invokes undefined behaviour)

You pass the nhap a pointer to char (char *) you then allocate memory to it, C (and C++ in this instance) passes by value, so you passed in the value of a[i], when memory is allocated in nhap the value of a[i] in main is left unchanged so when you try and free it in main you are freeing a random (and invalid) pointer.

This is why your program fails with free in main (where the address of the allocated memory is lost) and works when the free statement is in nhap.

If you want to return the value of the allocated pointer then either return it as the return value of the function or declare nhap as taking char ** and pass a pointer to the pointer to the function.

In the general case fo type T to return a value of type T from a function via a parameter then the code must have the structure

Expand|Select|Wrap|Line Numbers


Surprisingly,the program creates an error when i compile and test it!!
The error message is follow(I''m using MSVC++ 6.0):
Debug assertion failed!
Program......exe
File dbgheap.c
Expression CrtIsValidHeapPointer(pUserData)
Press Abort or Retry or Ignore..
Something with the heap??
P/S:Another problem,if i use new and delete,what should I write? delete a[i] or delete []a[i]??Don''t be annoyed because I''m confused on using pointers:books say that when delete a BLOCK of mem allocated by delete,I have to use delete []..!


这篇关于困惑于内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆