c - realloc() 浪费了很多空间,我做错了什么?

标签 c memory heap-memory realloc

所以,我在做这个练习:

Write a C function void occurrences(char* s, char c, char*** occp, int* n) that, given a string s and a char c, counts the number of occurrences of char c in the string s, returns that number in n and returns in occp the adress of a new array of char that contains the adresses of each c occurrence in s

main sample:

#include <stdio.h>

int main(){
    int i, n;
    char** occ;
    occorrenze("engineering", 'n', &occ, &n);
    for (i=0; i<n; ++i) printf("%s\n", occ[i]); // prints ngineering neering ng
    free(occ);
}

最初我是这样写函数的:

void occurrences(char* s1, char c, char*** s, int* n){
    *n=0;
     char* arr[2];
     int length=strlen(s1);
     int i;
     for(i=0; i<length; i++){
        if(s1[i]==c)(*n)++;
     }
     *s=(malloc((*n)*sizeof(char**)));
     int a=0;
     for(i=0; i<length; i++){
        if(s1[i]==c){
           (*s)[a]= &s1[i];
           a++;
        }
     }
}

效果很好,但我想尝试重写它,只迭代字符串一次。我想到了使用 realloc(),这是我以前从未使用过的函数,最终我想到了这个:

void occurrences(char* s1, char c, char*** s, int* n){
    *n=0;
    *s=malloc(0);
     char* arr[2];
     int length=strlen(s1);
     int i,a=0;
     for(i=0; i<length; i++){
        if(s1[i]==c){
            (*n)++;
            *s=realloc(*s,(*n)*sizeof(char**));
            (*s)[a]= &s1[i];
            a++;

        }
     }
}

这个似乎也工作得很好,但后来我运行了 Valgrind:

==4893== HEAP SUMMARY:
==4893==     in use at exit: 0 bytes in 0 blocks
==4893==   total heap usage: 4 allocs, 4 frees, 48 bytes allocated
==4893== 
==4893== All heap blocks were freed -- no leaks are possible
==4893== 
==4893== For counts of detected and suppressed errors, rerun with: -v
==4893== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

分配了 48 个字节?它应该是 24 个字节,对吧? 总堆大小为 8*n!而不是 8*n...我想我错过了一些东西 XD

编辑:复制了正确的函数哈哈

最佳答案

valgrind 不会测量整个应用程序执行期间分配的内存总量吗?

0 + 8 + 16 + 24 = 48。

关于c - realloc() 浪费了很多空间,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23792297/

相关文章:

linux - VirtualBox 设备上没有足够的剩余空间

c - 使用 if 语句与 #if 语句的区别

c - 警报处理程序中 swapcontext 后的段错误

c++ - 有没有办法获取堆上可用的内存地址范围?

c# - 什么时候为变量分配内存,是在声明时还是在初始化时?

java - Netbeans,分布式 Jar 文件,增加堆大小

c - 了解 malloc()

c++ - 如何在c中使用socket编程保存图像数据

c - 如何将 .h 文件中的外部符号验证为 .c 文件?

java - 作为递归参数的查找对象