jav321
jav321

Reputation: 169

C++ Pointer increment query

I have a working code for a function which takes a character and a number and forms a string by duplicating that character that number of times. Here is a piece that works perfectly fine.

char * buildstr(char c, int n)
{ 
   char * pc = new char[n+1];
   for (int i = 0; i < n; ++i)
   {
      *(pc+i) = c;
   }

   *(pc+n) = '\0';
   return pc;
}

But if I use another logic where I directly increment the pointer itself directly then I get an error when I free up the memory in the main function using delete [].

What could be my problem ?

Thanks,

char * buildstr(char c, int n)
{ 
   char * pc = new char[n+1];
   for (int i = 0; i < n; ++i)
   {
      *pc = c;
      pc++;

   }
   *(pc) = '\0';
   return pc;
}

Upvotes: 1

Views: 414

Answers (3)

juanchopanza
juanchopanza

Reputation: 227608

The problem is that you're returning the incremented pointer. delete[] has to be invoked with a pointer value that was returned by a call to new[], otherwise you get undefined behaviour. The same applies to calls to free and pointers returned by malloc, calloc etc.

Upvotes: 7

pabloxrl
pabloxrl

Reputation: 295

In the second example, you are incrementing the value of the pointer. When you try to delete it, it is pointing to the last position of the array.

This way, when you call delete[] on it, it crashes as it expects pc to point to the address that was originally allocated using new[].

I encourage you to use the first approach as you will be able to keep track of the base address through the lifetime of pc. Moreover, I think it would be easier for you to do this using array notation.

Consider using:

pc[i] = c;

instead of

*(pc+i) = c;

As it is more idiomatic and easy to read. If you are simply exercising your pointer arithmetic, stick to the first approach that you described.

Upvotes: 2

leykan
leykan

Reputation: 389

In the first function let's say that your pointer start at 0x00100. when you do the loop you get to the next adress so for exemple let's say 4 loop:

0x00100
0x00101
0x00102
0x00103

but at the end you return the pointer on the 0x00100 beceause you used index *(pc+i) where i is the index, so it is good.

Now on the second function you are doing the same exept that your are moving your pointer itself without index so you return your pointer at the last adress

0x00103

That is wy your second function doesn't work

Upvotes: 0

Related Questions