所以,我在做这个练习:
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/