为什么strcat的结果为空

 {"avgCordinates":[103.97242539990099,1.33518],"avgType": 1.6,}
 

结果为空。

但是如果我使用

char* path = malloc(128);
path = "/bin/"
char* path2 = malloc(128);
path2 = "ls"
strcat(path,path2);
fprintf(stderr,"%s\n",path);

之间有什么区别 char path [128]和malloc?

raincraft 回答:为什么strcat的结果为空

在下面的代码中

char* path = malloc(128);
path = "/bin/";                   //added ;,you're overwriting the returned pointer
char* path2 = malloc(128);
path2 = "ls";                     // same as above
strcat(path,path2);               // the destination buffer is non-modifiable!!
fprintf(stderr,"%s\n",path);

您实际上要覆盖分配器函数返回的内存(指针),并且使这些指针指向字符串文字。因此,strcat()调用会调用未定义的行为,因为目标缓冲区是不可修改的(因为它们是字符串文字)。这将调用undefined behaviour

第二个片段的问题较少

char path[128] = "/bin/";   // this is to be used as destination,OK
char* path2 = malloc(128);
path2 = "ls";               // you wouldn't need malloc here            
strcat(path,path2);
fprintf(stderr,path);

在这里,您正在分配足够大的数组(该数组可以修改,并且可以用作strcat()的合法目标缓冲区),因此从这个角度来看,您还可以。但是,对于第二个参数,您再次覆盖了malloc()返回的指针,从而导致内存泄漏。您无需在这里使用malloc(),只需将文字分配给指针并将其用作strcat()调用中的第二个参数。

,

char*在其他语言中的工作方式不同于“字符串类型”。它是一个指针,因此在您编写时:

char* path = malloc(128);
path = "/bin/"

malloc返回的内存由于丢失了指向它的指针而泄漏。

然后,当您尝试将内存串联到保存文字"/bin/"的内存中时,由于试图修改支持字符串文字的内存,您将得到未定义的行为。

,

让我为您注释这些...

第一个示例泄漏256个字节的内存,并且可能崩溃,具体取决于常量在内存中的位置。

// Declare pointer path; malloc 128 bytes of heap memory and assign the address
char* path = malloc(128);
// Reassign the pointer (losing track of the malloc) to a string constant
// (could be in read-only memory if the compiler has deemed it wise)
path = "/bin/";
// Declare pointer path2; malloc 128 bytes of heap memory and assign the address
char* path2 = malloc(128);
// Reassign the pointer (losing track of the malloc) to a string constant
// (could be in read-only memory if the compiler has deemed it wise)
path2 = "ls";
// Attempt to concatenate strings; if `path` resides in read-only memory,this will segfault.
strcat(path,path);

第二个示例泄漏了128个字节的内存,但不应崩溃(使用这些值;例如,使用用户输入,则必须小心使用strncat)。

// Declare pointer path to point to 128 bytes of stack memory (assuming in-function)
// and initialize it to "/bin/"
char path[128] = "/bin/";
// Declare pointer path2; malloc 128 bytes of heap memory and assign the address
char* path2 = malloc(128);
// Reassign the pointer (losing track of the malloc) to a string constant
// (could be in read-only memory if the compiler has deemed it wise)
path2 = "ls";
// Concatenate path2 to path in stack memory; this is fine (but could overflow)
strcat(path,path);

正确的方法应该是这样的(如果您不打算返回path,它是堆栈分配的)。但这并不能解决溢出问题。

// Declare pointer path to point to 128 bytes of stack memory (assuming in-function)
// and initialize it to "/bin/"
char path[128] = "/bin/";
// Concatenate the constant "ls" to path in stack memory (could still overflow)
strcat(path,"ls");
fprintf(stderr,path);
本文链接:https://www.f2er.com/1476207.html

大家都在问