简体   繁体   English

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

[英]Appending Strings Using Pointers In C

For the life of my I cannot figure out why this program is not working. 对于我的生活,我无法弄清楚为什么这个程序不起作用。 I'm trying to concatenate two strings using pointers and keep receiving this error: 我正在尝试使用指针连接两个字符串并继续收到此错误:

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

My str_append.c: 我的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';


}

I have my own strlength function which I'm 100% sure works. 我有自己的strlength函数,我100%肯定有效。

My main.c: 我的主要内容:

#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;
}

I've tried reallocating to a temporary variable and receive the same error. 我已经尝试重新分配到临时变量并收到相同的错误。 Any help is appreciated. 任何帮助表示赞赏。

EDIT: Thanks for all the answers. 编辑:谢谢你的所有答案。 This site is awesome. 这个网站太棒了。 Not only do I know where I went wrong (simple mistake I guess), but I found a pretty big hole in what I didn't know about strings. 我不仅知道自己哪里出错了(我猜是简单的错误),但我发现了一个关于字符串的不了解的漏洞。 Since I can't use the strcpy function I've implemented my own. 由于我不能使用strcpy函数,我已经实现了自己的。 It's the source code for strcpy basically. 它基本上是strcpy的源代码。

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

Your problem is here 你的问题在这里

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

First you allocate space for 1000 chars and point your pointer to the beginning of that memory. 首先,为1000个字符分配空间,并将指针指向该内存的开头。
Then in the second line you point your pointer to a string literal causing a memory leak. 然后在第二行中,将指针指向一个导致内存泄漏的字符串文字。
You pointer no longer points to the allocated memory. 指针不再指向分配的内存。
And later in your function you try to change the string literal which is read-only. 稍后在函数中,您尝试更改只读的字符串文字。

You're attempting to realloc a pointer to a static variable. 您正在尝试重新分配指向静态变量的指针。 When you set 当你设置

str = "Hello";

You're statically assigning that variable (ie it will be assigned at compile time). 您静态分配该变量(即它将在​​编译时分配)。 It is then not a valid pointer to use for other purposes, including realloc . 不是用于其他目的的有效指针,包括realloc You're also wasting all of the space you retrieved with malloc on the line above by throwing away your only pointer to that memory. 你也浪费了你在上面一行中使用malloc检索到的所有空间,扔掉你唯一指向该内存的指针。

What you need to do instead is to use strcpy to assign the value: 你需要做的是使用strcpy来赋值:

strcpy(str, "Hello");

Then you still have a dynamically allocated pointer, which you can use for realloc . 然后你仍然有一个动态分配的指针,你可以用它来realloc

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

should be: 应该:

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

The former allocates some memory and stores the address of that memory into the str pointer, then changes the str pointer to point to different (unmalloced) memory. 前者分配一些内存并将该内存的地址存储到str指针中,然后将str指针更改为指向不同 (未定位)的内存。

That's why you're seeing pointer being realloc'd was not allocated . 这就是为什么你看到pointer being realloc'd was not allocated

The latter code segment leaves str pointing at the malloced memory and just copies the string into that memory. 后一个代码段使str指向malloced内存,只是将字符串复制到该内存中。


And, as an aside, you should never cast the return value from malloc in C - it can hide certain subtle errors and it's unnecessary since C is perfectly capable of implicitly casting the void* returned into any other pointer type. 而且,顺便说一下,你永远不应该在C语言中从malloc返回值 - 它可以隐藏某些微妙的错误而且它是不必要的,因为C完全能够隐式地将void*返回到任何其他指针类型中。

Also, since sizeof(char) is always one, you never need to multiply by it. 此外,由于sizeof(char)总是一个,所以你永远不需要乘以它。 It usually clutters the code unnecessarily. 它通常会不必要地混乱代码。

Lastly, though probably not too important in this case, the C standard reserves identifiers beginning with str , mem and wcs (each followed by a lowercase letter) for future library directions, so you may want to reconsider your use of things like strlength() if you want future portability. 最后,尽管在这种情况下可能不太重要,但C标准保留了以strmemwcs开头的标识符(每个标识符后面跟一个小写字母)以用于将来的库方向,因此您可能需要重新考虑使用strlength()类的东西如果你想要未来的便携性。

strings literals (ex : "MAMA" "MEME" ) are immutable. 字符串文字(例如: "MAMA" "MEME" )是不可变的。 you cant reallocate them, however, if you use pointer of chars (ex. char * s = (char*)malloc(sizeof(char) * LEN ) and allocate them then they are mutable. 但是,如果你使用字符指针(例如char * s = (char*)malloc(sizeof(char) * LEN )并分配它们,那么你就不能重新分配它们,那么它们是可变的。

here : 这里 :

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

you should use built-in functions in string manipulation... 你应该在字符串操作中使用内置函数......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM