在C字符串动态内存分配 [英] dynamic memory allocation for strings in c

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

问题描述

我发现这个code完美的工作。

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);
        }
    }
}

我不明白的是,如何在字符串s存储在memory.i我只为指针s,这是4 bytes.Now哪里由用户给定的输入字符串获取存储在分配内存?

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?

推荐答案

这只是第一个四个字节的安全。第五个字节溢出对别的东西,这将产生不确定的行为已分配数据和流浪汉(可能会崩溃,可能不会)。

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).

此外,你不空终止字符串'\\ 0'后,你写完的字符,所以当你试着和它调用一个字符串例程(strcpy的),你可能会介绍另一个崩溃 - 除非内存后您的字符串正好包含零无论如何,但当然,你不应该依赖这个机会!

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!

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

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