简体   繁体   English

如何清除传递给C中的函数的char *?

[英]How to clear a char* passed to a function in C?

How can i make a function to clear a C string and/or free the allocated memory? 如何使函数清除C字符串和/或释放分配的内存? Why the following code does not work? 为什么以下代码不起作用?

void freeStr(char** str) {
    free(*str);
}
int main() {
    char* str = "some string";
    freeStr(&str);
    printf("%s", str);
    return 0;
}

You can neither free nor clear the memory of the array that a string literal denotes. 您既不能释放也不能清除字符串文字所表示的数组内存。

However, to lose access to it, all you need is to change the pointer you've stored its address in: 但是,要失去对它的访问权限,您只需要更改存储其地址的指针:

str = NULL; // in main
// or
*str = NULL; // in freeStr

The string you allocated is in the CONST_DATA section (cannot be modified) and hence, you cannot call free on it. 您分配的字符串位于CONST_DATA部分(无法修改),因此您无法在其上调用free。

That part of memory is allocated at compile time and is read only. 内存的这一部分在编译时分配,只读。 That part of memory still holds "some string\\0" 内存的那部分仍然保留"some string\\0"

The CONST_DATA section, in assembly is like the data-segment (DS), which contains global and static (read-only) variables initialized at compile time itself. 汇编中的CONST_DATA部分类似于数据段(DS),它包含在编译时自身初始化的全局和静态(只读)变量。 They do not change during runtime, and remain allocated to the running program. 它们在运行时不会更改,并保持分配给正在运行的程序。

You might find it helpful to go over the C FAQ - malloc section . 您可能会发现查看C FAQ - malloc部分很有帮助。

As others have noted, you can't free or modify string literals as they are usually placed in read only sections of memory. 正如其他人所说,你不能释放或修改字符串文字,因为它们通常放在内存的只读部分。 However, if you wish to clear and free() dynamically allocated memory, you'd do something like the following: 但是,如果您希望清除并free()动态分配的内存,您可以执行以下操作:

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

#define LENGTH  20

void freeStr(char **str)
{
    free( *str );
    *str = NULL;   
}

int main() {

    char *str = malloc( sizeof(char) * LENGTH);

    // clear that allocated memory
    memset( str, 0x00, LENGTH );

    // Put some text into the memory
    strncpy( str, "Some text", LENGTH-1 );

    printf("Before: %s\n", str);


    freeStr(&str);
    // string is now NULL and the memory is free.
    printf("After: %s\n", str);

    return 0;
}

http://en.cppreference.com/w/c/memory/free http://en.cppreference.com/w/c/memory/free

void free( void* ptr ); void free(void * ptr);

Deallocates the space previously allocated by malloc(), calloc() or realloc(). 释放先前由malloc(),calloc()或realloc()分配的空间。 If ptr is null-pointer, the function does nothing. 如果ptr是空指针,则该函数不执行任何操作。

Your string is not allocated with any of these functions. 您的字符串未分配任何这些功能。 I think is this way. 我想是这样的。

void freeStr(char **str) {
    *str = NULL;
}
int main() {
    char* str = (char *)"some string";
    printf("Before: %s\n", str);
    freeStr(&str);
    printf("After: %s\n", str);
    return 0;
}

The answers are pretty good, but there are a few points that they've missed or omitted. 答案非常好,但有几点他们错过或遗漏了。 Your question is also slightly vague. 你的问题也有些模糊。

If you want to clear a C string you overwrite the memory space that it points to with null bytes. 如果要清除C字符串,则用空字节覆盖它指向的内存空间。 You can only free() a C string that has been allocated by the heap allocator via a call to one of the heap allocator functions such as malloc() , calloc() or realloc() etc. 您只能通过调用其中一个堆分配器函数(如malloc()calloc()realloc()calloc() free()由堆分配器分配的C字符串。

So if you allocated a string using malloc() , or one of the other heap allocation functions, like so and then copied a string into it, you could clear it by calling memset() , but you would still then have to call free() to release that memory back to the heap. 因此,如果你使用malloc()或其他堆分配函数之一分配了一个字符串,然后将一个字符串复制到其中,你可以通过调用memset()清除它,但是你仍然需要调用free()将该内存释放回堆中。

For example: 例如:

char* strPtr = malloc(32); // allocate 32 bytes of storage off the heap
strcpy(strPtr, "test");    // copy a string into the newly allocated block on the heap
memset(strPtr, 0, 32);     // clear the allocated block
free(strPtr);              // return the allocated block to the heap

Also, note that C uses block scope and you do not have to explicitly deallocate arrays which were declared with the default storage class, auto, as they are popped off of the stack frame when that block goes out of scope. 另外,请注意C使用块作用域,您不必显式释放使用默认存储类auto声明的数组,因为当该块超出作用域时,它们会从堆栈帧中弹出。

void foo() {
    char strArray[32];          // this is a stack allocation
    strcpy(strArray, "test");   // copy a string onto the stack
    return;                     // no call to free() required
}

Finally, yet another method of allocation is static. 最后,另一种分配方法是静态的。 When you use the declaration: 当您使用声明时:

char* str = "literal string";

The space for the string "literal string" resides in a statically allocated segment which should never be written to. 字符串“literal string”的空间位于静态分配的段中,该段永远不应写入。 On some platforms, you will get a segfault if you try to write to that memory segment. 在某些平台上,如果您尝试写入该内存段,则会出现段错误。 You should not attempt to clear memory blocks that were statically allocated as there is no guarantee that the segment which they are mapped into is writable. 您不应尝试清除静态分配的内存块,因为无法保证它们映射到的段是可写的。

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

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