Question

I have an array allocated with malloc:

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

And then I filled this memory:

strcpy(aStr1, "ABCDEFGHI");

After that I created a new pointer aStr2:

char *aStr2 = aStr1 + 5;

And i set fourth element of memory to '\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.

How i can implement this function? (I read many linux mans about allocs function and haven't found any information about such problem).

//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

//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.

Was it helpful?

Solution

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.

OTHER TIPS

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. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top