简体   繁体   English

c中字符串的动态内存分配

[英]dynamic memory allocation for strings in c

I found this code working perfectly. 我发现这段代码可以正常工作。

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




int main(int argc,char *argv[])
{
    char* s;        /* input string */
    s=malloc(sizeof(s));    

    int c;

    if(argc==1){ // if file name not given


        while (gets(s)){
            puts(s);
        }
    }
}

What I don't understand is, how is the string s stored in memory.i am allocating memory only for the pointer s, which is of 4 bytes.Now where does the input string given by the user get stored in? 我不明白的是,字符串s是如何存储在内存中的。我只为4个字节的指针s分配内存,现在用户输入的字符串存储在哪里?

Rather than this you should do 而不是您应该这样做

s=malloc(sizeof(*s)*(number_of_chars+1)); 

You set number_of_chars to appropriate value, so that you allocate memory to store those many characters. 您可以将number_of_chars设置为适当的值,以便分配内存来存储许多字符。 +1 is for last '\\0' character. +1是最后一个'\\0'字符。

With your approach you are allocating 4 bytes so you can store usually those many characters. 使用您的方法,您将分配4 bytes因此通常可以存储许多字符。

You've allocated sizeof(void*) bytes of memory and filling it with user-provided data. 您已经分配了sizeof(void*)个字节的内存,并用用户提供的数据填充了它。 You have an address and writing to it, it's ok from compiler's point of view (maybe it's really what you want, who knows). 您有地址并写了地址,从编译器的角度来看是可以的(也许是您真正想要的,知道的人)。 Even if you program didn't crash when you exceed it - it's still an error. 即使您的程序在超出时没有崩溃,它仍然是一个错误。 It's just a memory, something else could be stored in this area, and you'll overwrite it - so expect heavy trouble if you'll ever do that. 它只是一个内存,可能在此区域中存储其他内容,并且您将覆盖它-因此,如果您这样做的话,会遇到很大的麻烦。

It's only safe for the first four bytes. 仅对于前四个字节是安全的。 The fifth byte will overrun the allocated data and tramp on something else which will yield undefined behaviour (might crash, might not). 第五个字节将超出分配的数据,并踩到其他东西,这将导致未定义的行为(可能会崩溃,可能不会)。

Also, you don't null terminate the string with '\\0' after you finish writing the chars, so you'll probably introduce another crash when you try and call a string routine (strcpy) on it - unless the memory after your string happened to contain zeros anyway, but naturally you shouldn't rely on this chance! 另外,在编写完字符后,您不要以'\\ 0'终止字符串,因此,当您尝试在其上调用字符串例程(strcpy)时,可能会导致另一次崩溃-除非字符串后的内存碰巧还是包含零,但是自然地您不应该依赖这个机会!

It's possible as compiler assigns two bytes. 编译器可能会分配两个字节。 now you give 10 bytes in input, so your allocated memory overflows and data stored beyond your allocated memory only if its available. 现在您输入了10个字节,因此分配的内存溢出,并且只有在可用的情况下,数据才会超出分配的内存存储。

It might give error if the data you want to store is greater then available and not give error if the data you want to store is greater then allocated. 如果要存储的数据大于可用数据,则可能会出错;如果要存储的数据大于分配数据,则可能不会出错。

puts will print data until it gets '\\0'. puts将打印数据,直到得到'\\ 0'。

So this is expected behavior!! 所以这是预期的行为!!

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

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