C语言 为 char* C 语言分配内存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2971709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allocating memory to char* C language
提问by boom
Is it the correct way of allocating memory to a char*.
这是将内存分配给 char* 的正确方法吗?
char* sides ="5";
char* tempSides;
tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
回答by Claudiu
Almost. Strings are NULL terminated, so you probably want to allocate an extra byte to store the NULL byte. That is, even though sidesis 1 character long, it really is 2 bytes: {5,'\0'}.
几乎。字符串以 NULL 结尾,因此您可能需要分配一个额外的字节来存储 NULL 字节。也就是说,即使sides是 1 个字符长,它也确实是 2 个字节:{ 5、'\0'}。
So it would be:
所以它会是:
tempSides = (char *)malloc((strlen(sides)+1)*sizeof(char));
and if you wanna copy it in:
如果你想复制它:
strcpy(tempSides, sides);
回答by jweyrich
Note that:
注意:
- Strings are zero-terminated (\0), and strlen() doesn't count it;
- By definition, sizeof(char) is 1 (byte), so it's not required;
- If you use a C (not C++) compiler, there's no need to cast it to
char *;
- 字符串以零结尾(\0),strlen() 不算;
- 根据定义,sizeof(char) 是 1(字节),所以它不是必需的;
- 如果您使用 C(不是 C++)编译器,则无需将其强制转换为
char *;
So that would be:
所以那将是:
char *tempSides = malloc(strlen(inSides) + 1);
Still, if you want to duplicatethe contents of inSides, you can use strdup, e.g.:
不过,如果你想复制的内容inSides,你可以使用strdup,例如:
char *tempSides = strdup(inSides);
if (tempSides != NULL) {
// do whatever you want...
free(tempSides);
}
回答by R Samuel Klatchko
As has been pointed out, you missed allocating space for the terminating NUL chararacter. But I also wanted to point out a couple of other things that can make your code more concise.
正如已经指出的那样,您错过了为终止 NUL 字符分配空间。但我还想指出其他一些可以使您的代码更加简洁的事情。
By definition, sizeof(char)is always 1, so you can shorten your allocation line to:
根据定义,sizeof(char)始终为 1,因此您可以将分配行缩短为:
tempSides = (char*)malloc(strlen(inSides) + 1);
Another thing is that this looks like you are doing to duplicate the string. There is a built in function that does that for you:
另一件事是,这看起来像是在复制字符串。有一个内置函数可以为您执行此操作:
tempSides = strdup(inSides);
This handles getting the length, allocating the correct number of bytes and copying the data.
这将处理获取长度、分配正确的字节数和复制数据。
回答by Vagrant
There's a problem with that. tempSides will point to an uninitialized block of memory of size 1. If you intend to copy the sides string into tempSides, then you will need to allocate a size one byte longer, in order to hold the zero terminator for the string. The value returned by strlen() does not include the zero terminator at the end of the string.
这有问题。tempSides 将指向一个大小为 1 的未初始化内存块。如果您打算将 side 字符串复制到 tempSides 中,那么您将需要分配一个长一字节的大小,以保存字符串的零终止符。strlen() 返回的值不包括字符串末尾的零终止符。
回答by Jerry Coffin
No, not really. As others have already noted, you need to allocate space for the NUL terminator.
不,不是真的。正如其他人已经指出的那样,您需要为 NUL 终止符分配空间。
In addition, you generally should notcast the return from malloc. It can cover up a bug where you've forgotten to #includethe correct header. Multiplying by sizeof(char)is also pointless, since the standards (both C and C++) define sizeof(char)to always be 1.
此外,你一般应不投的回报malloc。它可以掩盖您忘记#include正确标题的错误。乘以sizeof(char)也是毫无意义的,因为标准(C 和 C++)定义sizeof(char)为始终为 1。
Finally, every call to mallocshould include a test of the result. I'd wrap the whole thing up into a function:
最后,每次调用都malloc应该包括对结果的测试。我会把整个事情包装成一个函数:
char *dupe_string(char const *string) {
char *temp;
if (NULL!=(temp=malloc(strlen(string)+1)))
strcpy(temp, string);
return temp;
}
回答by AnT
Multiplying the element count by sizeof(char)is a matter of personal preference, since sizeof(char)is always 1. However, if you do this for consistency, better use the recipient pointer type to determine the element size, instead of specifying type explicitly. And don't cast the result of malloc
乘以元素计数sizeof(char)是个人偏好的问题,因为sizeof(char)它总是 1。但是,如果为了一致性而这样做,最好使用接收者指针类型来确定元素大小,而不是明确指定类型。并且不要投射结果malloc
tempSides = malloc(strlen(inSides) * sizeof *tempSides);
Of course, when working with zero-terminated strings you have to remember to allocate extra space for the terminating zero character. There's no way to say whether it is your intent to make tempSidesa zero-terminated string in this case, so I can't say whether you need it.
当然,在使用以零结尾的字符串时,您必须记住为结尾的零字符分配额外的空间。tempSides在这种情况下,无法确定您是否打算制作以零结尾的字符串,因此我无法确定您是否需要它。
回答by Pankaj Kumar Thapa
The correct way of allocation dynamic memory to tempSidesis as shown below:
正确的动态内存分配方式tempSides如下图:
char* sides ="5";
char* tempSides;
tempSides = (char*)malloc((strlen(sides) + 1) * sizeof(char));
char*stores a string data, similar to char[]. Strings are null (\0)terminated. So extra one byte should be allocated for nullcharacter storage.
char*存储一个字符串数据,类似于char[]. 字符串被null (\0)终止。所以应该额外分配一个字节用于null字符存储。
Dynamically allocated memory block must be freed using free()after it's use is over. If not freed, memory leak would happen.
动态分配的内存块必须在使用free()结束后释放使用。如果不释放,就会发生内存泄漏。
free(tempSides);
One the memory is freed, NULLmust be assigned to prevent it from being a dangling pointer.
一个内存被释放,NULL必须被分配以防止它成为一个悬空指针。
tempSides = NULL;

![C语言 char a[]=](/res/img/loading.gif)