简体   繁体   English

如何在结构体中为c中的字符串创建内存分配?

[英]How to create memory allocation in a struct for a string in c?

I have a bit of an issue. 我有一个问题。 I'll explain, I'm trying to create a dynamic memory allocation for a string inside a struct and print it. 我将解释,我正在尝试为结构内的字符串创建动态内存分配并打印它。 The thing is, it doesn't care about the size I dynamically allocate. 问题是,它并不关心我动态分配的大小。

For example, I create a string in the size of size 6, but it let's me insert 15 chars and prints them all. 例如,我创建了一个大小为6的字符串,但让我们插入15个字符并将其全部打印出来。

So basically, it doesn't limit me on the string size, why's so? 因此,基本上,它不限制我的字符串大小,为什么呢?

typedef struct{
    int grade;
    int id;
    int arr[5];
    char *str;
}student;

int main(){
    puts("How many many letters in char?\n");
    scanf("%d", &num);
    getchar();
    student1.str = (char *)malloc(sizeof(char)*num+1);
    gets(buffer);
    strcopy(student1.str, buffer);
}

BTW, I tried to keep the code clear as possible for you guys/ladies, just with the main things I need. 顺便说一句,我试图让你们/女士尽可能清楚地编写代码,以及我需要的主要内容。 I know I didn't free the memory or checked if allocation failed etc... 我知道我没有释放内存,也没有检查分配是否失败等。

First to say, please see this discussion on why not to cast the return value of malloc() and family in C . 首先要说的是, 请参阅有关为什么不在Cmalloc()和family的返回值的讨论。 .

Coming to the main issue here, out of bound memory access causes undefined behavior . 来到这里的主要问题, 超出范围的内存访问会导致未定义的行为

So basically, it doesn't limit me on the string size, why's so? 因此,基本上,它不限制我的字符串大小,为什么呢?

There is nothing in the C standard itself to prevent you from accessing out of bound memory ( ie, accessing the memory which is not allocated to your process ), but any attempt to do so will lead to UB. C标准本身没有什么可以阻止您访问超出范围的内存( 即访问未分配给您的进程的内存 ),但是任何尝试都会导致UB。 Don't do that . 不要那样做

That said, 那就是

  1. Never use gets() , it suffers from buffer overrun issues, use fgets() instead. 永远不要使用gets() ,它会遇到缓冲区溢出问题,请改用fgets()

  2. sizeof(char) is defined to be 1 in C. Using that as a multiplier is redundant. sizeof(char)在C中定义为1。将其用作乘法器是多余的。

The malloc is giving you the permission to write to the memory but you can try and write without permission. malloc授予您写入内存的权限,但是您可以尝试在没有权限的情况下进行写入。 That is what you just did. 那就是你刚才所做的。 It may work and it may not, but If you will use malloc properly you should be able to run this code run-time-error-free 它可能会工作,但可能不会,但是如果正确使用malloc,则应该可以运行此代码,且运行时无错误

When you use C, a major part of the job of programming, is to make sure that any data that hits your allocated memory will actually fit. 当您使用C时,编程工作的主要部分是确保击中您分配的内存的所有数据都将真正适合。 This is why C programming can be such a pain. 这就是为什么C编程如此痛苦。 It also requires you to free your memory when you don't use it anymore, which you forgot in your example. 它还要求您在不再使用内存时释放您的内存,这在您的示例中已被忘记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM