如果在已分配的内存上使用strdup会发生什么

问题描述

我的堆栈实现遇到问题,我的push函数操纵了我发送到函数中的值并对其进行了更改。我尝试了各种不同的构造方法,但它们要么不起作用,要么给我损坏的输出

基本思想是下面的思想,注意:我的pop函数仅沿一个位置走,而没有释放特定位置的内存。由于我正在使用线程,因此无法使用strcpy

strdup会更改它复制的值吗,我找不到任何信息说是这样,我的理解是,您应该能够在重复使用该值之后使用该值。

在已分配的内存空间上使用strdup的正确方法如何?我假设我不能只是释放它然后再次使用它。

void stack_push(Stack *s,char *value)
{
   if (s->size == s->capacity) {
       realloc_stack(s);
   }

   if(s->data[s->size] == NULL){
       // The current position does not contain any data.
       s->data[s->size] = strdup(value);

   }
   else{
       free(s->data[s->size]);
       s->data[s->size] = strndup(value,strlen(value) + 1);
   }

   s->size += 1;

}

编辑 s-> data = char ** data

解决方法

strdup基本上是这样(为了简洁起见,没有错误检查):

char *strdup(const char *stringtoduplicate)
{
  char *newstring = malloc(strlen(stringtoduplicate) + 1);
  strcpy(newstring,stringtoduplicate);
  return newstring;
}

您可以这样使用它:

char Foo[] = "Bar";
char *newBar = strdup(Foo);
Foo[0] = 'F';
printf("%s %s\n",Foo,newBar);   // prints: Far Bar
...
free(newBar);     // once you're done with newBar,free it

现在您应该可以回答自己的问题了。

,

class RevIter: def __init__(self,iterable): self.iterable = list(iterable) self.index = len(self.iterable) def __iter__(self): # if you want the instance to be able to reset the iteration,# redefine "self.index" here. # self.index = len(self.iterable) # this is what "iter(instance)" becomes: return self def __next__(self): self.index -= 1 if self.index < 0: raise StopIteration() return self.iterable[self.index] 不会以任何方式修改其参数。如果查看strdup的原型,您会看到其参数已声明为strdup,这意味着它没有被修改。

const可以实现为:

strdup

没有魔术。

顺便说一下,您可以将char* strdup(const char* s) { char* n = malloc(strlen(s) + 1); if (n) strcpy(n,s); return n; } 与线程一起使用。但是strcpy可以正常工作。