简体   繁体   English

如何知道两个C字符串是否指向一个内存块?

[英]How to know if two C-strings point to one memory block?

I have an array allocated with malloc: 我有一个分配了malloc的数组:

char *aStr1 = (char* ) malloc (10);

And then I filled this memory: 然后我填满了这段记忆:

strcpy(aStr1, "ABCDEFGHI");

After that I created a new pointer aStr2: 之后,我创建了一个新的指针aStr2:

char *aStr2 = aStr1 + 5;

And i set fourth element of memory to '\\0': 我将内存的第四个元素设置为“ \\ 0”:

*(aStr1 + 4) = '\\0'; *(aStr1 + 4)='\\ 0';

And finally, using these two pointers in a simple function: 最后,在一个简单的函数中使用以下两个指针:

int checkMem(char *aStr1, char *aStr2);

This function returns true (some none zero value) if aStr1 and aStr2 pointed to one memory block, and returns zero in another case. 如果aStr1和aStr2指向一个内存块,则此函数返回true(有些零)。在另一情况下,该函数返回零。

How i can implement this function? 我如何实现此功能? (I read many linux mans about allocs function and haven't found any information about such problem). (我读过许多关于allocs函数的Linux芒书,但尚未找到有关此类问题的任何信息)。

//Added //添加

I need this to do something like that: 我需要这样做:

char *aStr1 = (char *) malloc (10);
char *aStr2 = aStr1 + 5;
strcpy(aStr1, "ABCDEFGHI");
*(aStr1 + 4) = '\0';

and than: 然后:

my_strcat(aStr1, aStr2);

I do not ask for help to implement my_strcat, but maybe, get some hint how i can resolve its problem 我不寻求帮助来实现my_strcat,但也许可以得到一些提示,说明我如何解决其问题

//Updated //更新

thanx, for all. 感谢所有人。 I solved it. 我解决了

Without any low level functions you cannot correctly know, how many memory allocate (maybe on some platform or realization you can do this: 没有任何底层函数,您将无法正确知道多少内存分配(也许在某些平台或实现上,您可以这样做:

size_t ptr_size = *((size_t *)ptr - 1);

but maybe not for all it will be correct). 但可能并非全部正确)。

And solving is simple: i create local copy of aSrc2, then realloc aSrc1 and copy aSrc2 to new aSrc1. 解决方法很简单:我创建aSrc2的本地副本,然后重新分配aSrc1并将aSrc2复制到新的aSrc1。

Unfortunately you cannot tell if two pointers point to memory that belonged to the same initial allocation. 不幸的是,您无法确定两个指针是否指向属于同一初始分配的内存。

You can create classes/structures that, for instance, save the initial allocation and then you could compare them. 您可以创建类/结构,例如,保存初始分配,然后可以对其进行比较。

But without added information, you simply cannot tell. 但是,如果没有附加信息,您将无法分辨。

There is no provided standard mechanism for doing this, its up to you to track the memory you received and how big those allocations are, so you'd probably want to provide your own malloc wrapper that tracks what's allocd. 没有提供执行此操作的标准机制,它由您来跟踪收到的内存以及这些分配的大小,因此您可能希望提供自己的malloc包装器来跟踪分配的内容。 Store the pointers in a map so you can use lower_bound to find the nearest allocate to the first string and then check if the second string is in the same allocation. 将指针存储在映射中,以便您可以使用lower_bound查找与第一个字符串最近的分配,然后检查第二个字符串是否在同一分配中。

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

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