Jump to content

Assertion Error (Dynamic Memory Allocation)

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
LukeyJ

LukeyJ

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
Hi,

I'm getting an assertion error in the following script. I'm playing around with strings and trying to identify the string lengths of various ones. The first two worked great. When I tried to do the same thing dynamically. I ran into an assertion error which I am unfamiliar with. The output in the background works, but its taking a dislike to something.

Here is the code:

#include <string.h>

#include <iostream>


using namespace std;


int main () {

	char* str1 = "123456";

	char str2 [] = "123456789";

	char* pstr1 = NULL;

	pstr1 = new char[] = "1234567";


	cout << "Pointer to char length: " << strlen(str1) << endl

		<< "Array length: " << strlen(str2) << endl

		<< "Dynamic char array: " << strlen(pstr1) << endl;


	delete [] pstr1;

	pstr1 = NULL;


	return 0;

}

Any help would be greatly appreciated.

Thanks in advance,

Luke

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

Quote

main.cpp: In function `int main()':
main.cpp:10: error: expected primary-expression before ']' token
Are you sure it builds?

pstr1 = new char[] = "1234567";
Char arrays are not std::strings; use strcpy.

#3
LukeyJ

LukeyJ

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
The assertion error info I got was:

Debug Assertion Failed!

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

It does compile for me, but throws and assert error. The error will perhaps be on one of the following lines.

	char* pstr1 = NULL;
	pstr1 = new char[] = "1234567";

<< "Dynamic char array: " << strlen(pstr1) << endl;

	delete [] pstr1;
	pstr1 = NULL;

pstr1 = new char[] = "1234567"; is my guess.

Can you initiatate new memory for a character array without specifying a size? Would new char* = "12345"; be a better course of action?

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
I thought I mentioned using strcpy.
#include <string.h>
#include <iostream>

using namespace std;

int main ()
{
   char* str1 = "123456";
   char str2 [] = "123456789";
   [COLOR="Blue"]char* pstr1 = new char[sizeof("1234567")];
   strcpy(pstr1, "1234567");[/COLOR]

   cout << "Length of string pointed to by str1: " << strlen(str1) << endl
        << "Size of str2: " << sizeof(str2) << endl
        << "length of string in str2: " << strlen(str2) << endl
        << "Dynamic char array: " << strlen(pstr1) << endl;

   delete [] pstr1;
   pstr1 = NULL;

   return 0;
}

/* my output
Length of string pointed to by str1: 6
Size of str2: 10
length of string in str2: 9
Dynamic char array: 7
*/
BTW, I wouldn't recommend doing
char* pstr1 = new char[[COLOR="Magenta"]sizeof("1234567")[/COLOR]];
I'm just being lazy.