Debug error: Heap corruption detected

Debug error: Heap corruption detected

我在 C 中玩了一会儿,并尝试为 C 编程中的 oop 编写一个测试程序。我在 Visual Studio 2010 中收到标题错误。在使用 gcc 时,我没有收到此错误。

任何人都可以指出我做错了什么,除了使用错误的 oop 语言和其他偏离主题的建议。

当我在 string_dispose 中释放顶部 object 时似乎发生了错误,但我不确定这是否真的说明了错误的位置。

也欢迎任何有关代码改进的建议。使用数组语法不是一个选项,因为我想尝试指针算法。

header 文件 "strings.h":

#ifndef STRINGS_H
#define STRINGS_H

struct strings
{
    char* s;
    int len;
};

typedef struct strings string;

void string_init(string* s, char* chars, int len);

string* string_new(char* chars, int len);

void string_dispose(string* s);

#endif

源文件"strings.c":

#include "strings.h"
#include <stdlib.h>


void string_init(string* self, char* chars, int len)
{
    int i;

    self->s = (char*)malloc((len + 1) * sizeof(char*));
    for (i = 0; i < len; i++)
    {
        *(self->s + i) = *(chars + i);
    }
    *(self->s + len) = '[=11=]';
    self->len = len;
}


string* string_new(char* chars, int len)
{
    string* self;
    self = (string*)malloc(sizeof(string*));
    string_init(self, chars, len);
    return self;
}


void string_dispose(string* self)
{
    free(self->s);
    free(self);
}

主文件:

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


int main(int argc, char* argv)
{
    string* s;
    int n = 5;
    char* x = (char*)malloc((n + 1) * sizeof(char*));
    x[0] = 'f';
    x[1] = 'u';
    x[2] = 'b';
    x[3] = 'a';
    x[4] = 'r';
    x[5] = '[=12=]';
    s = string_new(x, n);   
    printf("the string: %s\n", s->s);
    printf("the length: %d\n", s->len);
    string_dispose(s);
    printf("This is way more important");
    return 0;
}

当您尝试为 string 分配内存时,您只为指针 (string*) 分配了足够的内存:

self = (string*)malloc(sizeof(string*));

您应该分配 sizeof(string),因为您需要足够的 space 来存储整个结构,而不仅仅是指向结构的指针。由于 sizeof(string*) 小于 sizeof(string),其他代码写入分配区域之外,导致堆损坏。

同理,为字符分配内存时,大小应为(len + 1) * sizeof(char)