簡體   English   中英

使用指針在C中追加字符串

[英]Appending Strings Using Pointers In C

對於我的生活,我無法弄清楚為什么這個程序不起作用。 我正在嘗試使用指針連接兩個字符串並繼續收到此錯誤:

a.out(28095) malloc: *** error 
for object 0x101d36e9c: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug

我的str_append.c:

#include <stdio.h>
#include <stdlib.h>
#include "stringlibrary.h"  /* Include the header (not strictly necessary here) */

//appends s to d
void str_append(char *d, char *s){
  int i=0, j=0;

  d = realloc(d, strlength(d)+strlength(s)+1);
  //find the end of d
  while(*(d+i)!='\0'){
    i++;
  }


  //append s to d
  while(*(s+j)!='\0'){
    *(d+i)=*(s+j);
    i++;
    j++;
  }
  *(d+i)='\0';


}

我有自己的strlength函數,我100%肯定有效。

我的主要內容:

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

int main(int argc, char **argv)
{
 char* str = (char*)malloc(1000*sizeof(char));
 str = "Hello";
 char* str2 = (char*)malloc(1000*sizeof(char)); 
str2 = " World";

str_append(str, str2);


 printf("Original String: %d\n", strlength(str));
 printf("Appended String: %d\n", strlength(str));


return 0;
}

我已經嘗試重新分配到臨時變量並收到相同的錯誤。 任何幫助表示贊賞。

編輯:謝謝你的所有答案。 這個網站太棒了。 我不僅知道自己哪里出錯了(我猜是簡單的錯誤),但我發現了一個關於字符串的不了解的漏洞。 由於我不能使用strcpy函數,我已經實現了自己的。 它基本上是strcpy的源代碼。

char *string_copy(char *dest, const char *src)
{
 char *result = dest;
 while (*dest++ = *src++);
 return result;
}

你的問題在這里

char* str = (char*)malloc(1000*sizeof(char));
str = "Hello";

首先,為1000個字符分配空間,並將指針指向該內存的開頭。
然后在第二行中,將指針指向一個導致內存泄漏的字符串文字。
指針不再指向分配的內存。
稍后在函數中,您嘗試更改只讀的字符串文字。

您正在嘗試重新分配指向靜態變量的指針。 當你設置

str = "Hello";

您靜態分配該變量(即它將在​​編譯時分配)。 不是用於其他目的的有效指針,包括realloc 你也浪費了你在上面一行中使用malloc檢索到的所有空間,扔掉你唯一指向該內存的指針。

你需要做的是使用strcpy來賦值:

strcpy(str, "Hello");

然后你仍然有一個動態分配的指針,你可以用它來realloc

char* str = (char*)malloc(1000*sizeof(char));
str = "Hello";

應該:

char* str = malloc (1000);
strcpy (str, "Hello");

前者分配一些內存並將該內存的地址存儲到str指針中,然后將str指針更改為指向不同 (未定位)的內存。

這就是為什么你看到pointer being realloc'd was not allocated

后一個代碼段使str指向malloced內存,只是將字符串復制到該內存中。


而且,順便說一下,你永遠不應該在C語言中從malloc返回值 - 它可以隱藏某些微妙的錯誤而且它是不必要的,因為C完全能夠隱式地將void*返回到任何其他指針類型中。

此外,由於sizeof(char)總是一個,所以你永遠不需要乘以它。 它通常會不必要地混亂代碼。

最后,盡管在這種情況下可能不太重要,但C標准保留了以strmemwcs開頭的標識符(每個標識符后面跟一個小寫字母)以用於將來的庫方向,因此您可能需要重新考慮使用strlength()類的東西如果你想要未來的便攜性。

字符串文字(例如: "MAMA" "MEME" )是不可變的。 但是,如果你使用字符指針(例如char * s = (char*)malloc(sizeof(char) * LEN )並分配它們,那么你就不能重新分配它們,那么它們是可變的。

這里 :

char* str = (char*)malloc(1000*sizeof(char));
str = "Hello"; //no error BUT wasted memory and cant be reallocated anymore (literal)

你應該在字符串操作中使用內置函數......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM