Hi

I´m doing homework and it ask for the strcpy function by using pointers.

This is my code but I always get some runtime error, don´t know why.

#include <iostream>
using namespace std;
void strcpy2(const char* source, char* destination);
int main()
{
	char* source = "Hello world";
	char* destination;
	strcpy2(source, destination);
	
system("pause");
return 0;
}
void strcpy2(const char* source, char* dest)
	{
	 while (*source != 0) 
	 {
        *dest = *source;
        dest++;
        source++;
	 }
    *dest = 0;  
}

Recommended Answers

All 2 Replies

You havn't allocated any memory at destination into which you can copy what is at source, so you are corrupting your data segment.

Your declaration of destination only causes the compiler to allocate four bytes (32 bit OS) for the char* itself. In terms of memory at which it 'points', you need to allocate that with new, malloc, GlobalAlloc(), HeapAlloc(), whatever.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void strcpy2(const char* source, char* dest)
{	 
 while (*source != 0)
 {
   *dest = *source; 
   dest++;
   source++;
 }
 *dest = 0;
}


int main()
{	
 char* source = "Hello world";
 char* destination=NULL;
 
 destination=(char*)malloc(strlen(source)+1);
 if(destination)
 {
    strcpy2(source, destination);
    puts(source);
    puts(destination);
    free(destination); 
    system("pause");
 }   
 
 return 0;
}

The other alternative is to declare an arbitrarily sized character array to serve as a buffer into which you can copy the string. If you absolutely know what the upper possible bound of what you are copying is, then its possible to do that. For example, if you knew the character string you were copying couldn't be over 63 characters, you could do this...

char szStringBuffer[64];
if(strlen(source)<64)
   strcpy2(source, szStringBuffer);
else
   puts("Buffer Not Big Enough!!!");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.