简体   繁体   English

字符串反转和缓冲区溢出

[英]String inversion and buffer overrun

I created a function to reverse a string.我创建了一个函数来反转字符串。

I know the code for this function is already available on the web but I'm starting to develop in C and I want to do my functions to understand what I'm doing.我知道这个函数的代码已经在网上可用,但我开始用 C 开发,我想做我的函数来理解我在做什么。

My Code:我的代码:

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


char* reverseString(char* chaineFonc);
    
    char* reverseString(char* chaineFonc)
    {
        // Initialization
        int stringLength = strlen(chaineFonc);
        char* response = (char*)malloc((stringLength + 1) * sizeof(char));
        int numCarac = stringLength - 1;
    
        // For each Character in the String
        for (int i = 0; i < stringLength; i++)
        {
            // Memorization
            response[i] = chaineFonc[numCarac];
    
            // Decrement
            numCarac--;
        }
        // End - For each Character in the String
    
        // Finalization
        response[stringLength] = '\0';
    
        return response;
    }


    int main(int nbArg, char** listeArg)
    {
        printf("\n%s",reverseString("ABCDEFGHIJKLMN"));
    }

This code works but I have an alert under Visual Studio which indicates a buffer overflow when I have this code response[stringLength] = '\0';此代码有效,但我在 Visual Studio 下有一个警报,指示当我有此代码时缓冲区溢出response[stringLength] = '\0';

And I don't understand why.我不明白为什么。

The Warnings:警告:

Avertissement C6011 Déréférencement du pointeur NULL 'response'.广告 C6011 Déréférencement du pointeur NULL“响应”。 (Dereferencing NULL pointer 'response') (取消引用 NULL 指针“响应”)

Avertissement C6386 Dépassement de la mémoire tampon lors de l'écriture sur 'response'.广告 C6386 Dépassement de la mémoire tampon lors de l'écriture sur 'response'。 (Buffer overflow while writing to 'response') (写入“响应”时缓冲区溢出)

You should have told us you were running the static code analysis which probably gave you these warnings:您应该告诉我们您正在运行 static 代码分析,它可能会给您以下警告:

C:\Users\XXX\main.c(30): warning C6386: Buffer overrun while writing to 'response':  the writable size is '((stringLength+1))*sizeof(char)' bytes, but 'stringLength' bytes might be written.
C:\Users\XXX\main.c(30): warning C6011: Dereferencing NULL pointer 'response'. 

You get warning C6011 because response can potentially be NULL , because malloc may return a NULL pointer, although this is very unlikely to happen, especially as the allocaterd size is very small.您会收到警告 C6011,因为response可能是NULL ,因为malloc可能会返回NULL指针,尽管这不太可能发生,尤其是很小的大小。

You can get rid of this warning by adding some code:您可以通过添加一些代码来消除此警告:

...
char* response = (char*)malloc((stringLength + 1) * sizeof(char));

if (response == NULL)  // <<< add this
  exit(1);             // <<< add this

int numCarac = stringLength - 1;
...

Warning C6386 is certainly a bug of the Microsoft static code analyzer, I don't see any problems in this code.警告 C6386 肯定是 Microsoft static 代码分析器的错误,我看不出这段代码有任何问题。 Especially as the following error message is contradictory:特别是因为以下错误消息是矛盾的:

`the writable size is '((stringLength+1))*sizeof(char)' bytes,
 but 'stringLength' bytes might be written`

It looks like you are using the malloc function to allocate memory for the response array, but you are not checking the return value of malloc to make sure that it succeeded.看起来您正在使用 malloc 函数为响应数组分配内存,但您没有检查 malloc 的返回值以确保它成功。 The malloc function returns a pointer to the allocated memory, or NULL if it was unable to allocate the requested amount of memory. malloc 函数返回指向已分配内存的指针,如果无法分配所请求的内存量,则返回 NULL。

You should check the return value of malloc before using the memory that it has allocated.在使用它分配的内存之前,您应该检查 malloc 的返回值。 Here is an example of how you could do this:这是您如何执行此操作的示例:

char* response = (char*)malloc((stringLength + 1) * sizeof(char));
if (response == NULL) {
    fprintf(stderr, "Error: Unable to allocate memory.\n");
    return NULL;
}

This will prevent a buffer overflow from occurring if malloc is unable to allocate the requested memory.如果 malloc 无法分配请求的内存,这将防止发生缓冲区溢出。

In addition, you should also consider using the calloc function instead of malloc, as it will initialize the allocated memory to zero, which can be useful in certain situations.此外,您还应该考虑使用 calloc 函数而不是 malloc,因为它将分配的内存初始化为零,这在某些情况下很有用。 The syntax for using calloc is similar to that of malloc, but it requires two arguments: the number of elements to allocate memory for and the size of each element.使用 calloc 的语法类似于 malloc,但它需要两个参数:要为其分配内存的元素数量和每个元素的大小。

For example:例如:

char* response = (char*)calloc(stringLength + 1, sizeof(char));
if (response == NULL) {
    fprintf(stderr, "Error: Unable to allocate memory.\n");
    return NULL;
}

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

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