0

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;  
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Frederick2
0

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

1

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!!!");

Edited by Frederick2: add alternative

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.