[英]using realloc to write on a new string?
remove_multiple 采用一個參數(一個 C 字符串),並刪除重復項。 它必須返回堆中動態分配的字符串。
我試圖:
the problem is that I still have this warning on the realloc: "C6308 'realloc' might return null pointer: assigning null pointer to 's', which is passed as an argument to 'realloc', will cause the original memory block to be泄漏”,當我嘗試調試程序時,我收到一條消息,它說我試圖在分配的 memory 之外寫入。
這是我的代碼:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char* remove_duplicates(const char* str) {
char* s = malloc(sizeof(char));
if (!s) {
return NULL;
}
for (size_t i = 0; str[i] != 0; i++) {
if (str[i] != str[i + 1]) {
s = realloc(s, 2 * sizeof(char));
if (!s) {
return NULL;
}
s[i] = str[i];
}
}
return s;
}
int main(void) {
char str[] = "heyyyy";
char* s = remove_duplicates(str);
printf("%s", s);
free(s);
return 0;
}
錯誤列表:
通常不需要為每個字符重新分配。 因此,懶惰的方法是最初分配一個與原始數組大小相同的數組,並在最后嘗試縮小它:
char* remove_duplicates(const char* str) {
char* s = malloc(strlen(str)); // only allocate once with original size
if (!s) {
return NULL;
}
// keep track or current position, size and previous character
char c, old = 0, *curr = s;
size_t n = 0;
while ((c = *str++) != '\0') {
// ignore duplicates
if (c != old) {
*curr++ = c;
old = c;
++n;
}
}
// add the terminating NULL
*curr = '\0';
// optional shrink attempt
s = realloc(s, n + 1);
return s;
}
首先,您的方法不好。
function 效率低下,因為其中有太多的 memory 重新分配。
至於消息那么這個
s = realloc(s, 2 * sizeof(char));
語句不安全,因為 function realloc
可以返回 null 指針。 在這種情況下,先前分配的 memory 的地址將丟失,從而導致 memory 泄漏。
您需要使用一個中間指針,該指針將被分配realloc
返回的值。
在這份聲明中
s = realloc(s, 2 * sizeof(char));
總是分配 2 個字節的 memory。
左側表達式中也使用了無效索引
s[i] = str[i];
^^^^
對於指針s
你需要支持它的一個索引而不是i
。
您首先需要確定有多少不重復的相鄰字符,然后只分配一次所需大小的數組。
這是一個演示程序。
#include <stdio.h>
#include <stdlib.h>
char * remove_duplicates( const char *s )
{
size_t n = 0;
for ( const char *p = s; *p; )
{
++n;
while ( *++p && p[0] == p[-1] );
}
char *result = malloc( n + 1 );
if ( result != NULL )
{
char *p = result;
do
{
*p = *s;
while ( *s++ && s[0] == s[-1] );
} while ( *p++ );
}
return result;
}
int main( void )
{
const char *s = "1223334444";
printf( "\"%s\"\n", s );
char *p = remove_duplicates( s );
if ( p ) printf( "\"%s\"\n", p );
free( p );
}
程序 output 是
"1223334444"
"1234"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.