LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Need help: Seg fault, Memcpy, and dynamically allocated arrays (http://www.linuxquestions.org/questions/programming-9/need-help-seg-fault-memcpy-and-dynamically-allocated-arrays-331949/)

benobi 06-09-2005 03:36 PM

Need help: Seg fault, Memcpy, and dynamically allocated arrays
 
I have the following and it seg faults at the line: delete [] buffer; i believe. can anyone tell me why? Also the output is: "hello world" followed by a space and some rectangle which i'm guessing is some non-standard ascii symbol. I thought memcpy's only supposed to copy over 5 bytes from string s?

Code:

#include <iostream>

using std::cout;
using std::endl;

int main()
{
  char * s = "hello world";
  char * buffer;
  int bufferSize = 15;

  memcpy(&buffer, &s, 5);

  for (int i = 0; i < bufferSize; i++)
  {
      cout << buffer[i];
  }
  cout << endl;

  delete [] buffer;

  return 0;
}

If i comment out the memcpy line, it doesn't seg fault.

vladmihaisima 06-09-2005 04:50 PM

Hello,

First buffer doesn't point to allocated memory. It points 'somewhere'. You must allocate space first, memcpy doesn't do that.

So:
buffer = new char(100); // c++ style
or
buffer = (char*)malloc(100*sizeof(char)); // c style

(edited this, I don't know why i was under impression it used printf :D)
Secondly, . By copying only the 5 charachters, you don't know what the 6th will be.
So you should print only what you copy.

Thrid: memcpy needs pointers to memory locations. Not pointers to pointers to memory locations. So you should do:
memcpy(buffer,s,5);

You should take it a little easier if you are new to c++. Maybe it would be a good idea to read one or two more tutorials.

;

rstewart 06-09-2005 04:55 PM

Hi,

You are actually copying the address of s into the address of buffer, not the contents of s. The reason for the seg fault is that when the program hits the delete [] buffer I believe that it is trying to free up memory that does not belong to the heap. The reason for printing out everything is because after the memcpy the buffer pointer points to the original data text.

I think what you are trying to do is:

Code:

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    char * s = "hello world";
    char * buffer = new char[16]; // Arbitrary length - big enough to hold all data
    int bufferSize = 15;

    memcpy(&buffer[0], &s[0], 5);

    for (int i = 0; i < bufferSize; i++)
    {
        cout << buffer[i];
    }
    cout << endl;

    delete buffer;

    return 0;
}


chrism01 06-09-2005 11:58 PM

Someone should have mentioned that you copy 5 chars to an arbitrary place in mem (ie into buffer var), but you are trying to print/cout 15(!) ie bufferSize chars....


All times are GMT -5. The time now is 09:19 PM.