为什么char指针比C中分配的内存节省更多的数据? [英] Why char pointer saving data more than allocated memory in C?

查看:175
本文介绍了为什么char指针比C中分配的内存节省更多的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中进行动态内存分配时,将内存大小分配给char指针时,我感到困惑.虽然我只给出1个字节作为限制,但是 char指针成功地尽可能长地输入了输入,因为每个字母都对应于1个字节.

While working on dynamic memory allocation in C, I am getting confused when allocating size of memory to a char pointer. While I am only giving 1 byte as limit, the char pointer successfully takes input as long as possible, given that each letter corresponds to 1 byte.

我也试图在输入前后查找指针的大小.我怎么知道这里发生了什么?输出使我感到困惑.

Also I have tried to find sizes of pointer before and after input. How can I understand what is happening here? The output is confusing me.

看下面的代码:

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

int main()
{
    int limit;

    printf("Please enter the limit of your string - ");
    gets(&limit);

    char *text = (char*) malloc(limit*4);

    printf("\n\nThe size of text before input is %d bytes",sizeof(text));

    printf("\n\nPlease input your string - ");
    scanf("%[^\n]s",text);

    printf("\n\nYour string is %s",text);

    printf("\n\nThe size of char pointer text after input is %d bytes",sizeof(text));

    printf("\n\nThe size of text value after input is %d bytes",sizeof(*text));

    printf("\n\nThe size of ++text value after input is %d bytes",sizeof(++text));

    free(text);



    return 0;


}

检查此输出:

推荐答案

它起作用,因为malloc通常不会分配与传递给它的字节数相同的字节数. 它保留多个块"的内存.通常,它会保留更多内存以缓存"它,以供下一次malloc调用用于优化. (这是特定于实现的) 例如,请查看 glibc malloc内部结构.

It works because malloc usually doesn't allocate the same number of bytes you pass to it. It reserves memory multiple of "blocks". It usually reserve more memory to "cache" it for next malloc calls as an optimization. (it is an implementation specific) check glibc malloc internals for example.

使用比malloc分配的内存更多的内存是未定义的行为.您可能会覆盖保存在堆上的malloc的元数据或破坏其他数据.

Using more memory than allocated by malloc is an undefined behavior. you may overwrite metadata of malloc saved on heap or corrupt other data.

我也试图在输入前后查找指针的大小.如何 我能理解这里发生了什么吗?输出使我感到困惑.

Also I have tried to find sizes of pointer before and after input. How can I understand what is happening here? The output is confusing me.

对于机器中的所有指针类型,指针的大小是固定的,取决于地址大小,通常为4/8字节.它与数据大小无关.

The size of pointer is fixed for all pointer types in a machine, it is usually 4/8 bytes depending on the address size. It doesn't have anything to do with data size.

这篇关于为什么char指针比C中分配的内存节省更多的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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