[LLVMdev] Another memory fun

Richard Pennington rich at pennware.com
Sun Jan 6 16:04:42 PST 2008


Zalunin Pavel wrote:
> but why this code don't work:
> 
> ; ModuleID = 'sample.lz'
> @.str1 = internal global [6 x i8] c"world\00"           ; <[6 x i8]*> 
> [#uses=1]
> @.str2 = internal global [7 x i8] c"hello \00"          ; <[7 x i8]*> 
> [#uses=1]
> @.str7 = internal global [7 x i8] c"father\00"          ; <[7 x i8]*> 
> [#uses=1]
> @.str8 = internal global [8 x i8] c"mother \00"         ; <[8 x i8]*> 
> [#uses=1]
> 
> declare i32 @puts(i8*)
> 
> declare i8* @strcat(i8*, i8*)
> 
> declare i32 @strlen(i8*)
> 
> declare void @llvm.memcpy.i32(i8*, i8*, i32, i32)
> 
> define i32 @main() {
> mainBlock:
>         %str3 = getelementptr [7 x i8]* @.str2, i64 0, i64 0            
> ; <i8*> [#uses=2]
>         %str4 = getelementptr [6 x i8]* @.str1, i64 0, i64 0            
> ; <i8*> [#uses=1]
>         call i8* @strcat( i8* %str3, i8* %str4 )                ; 

Right here you are copying str1 the memory address following the end of 
str2. Notice that str3 is a pointer to a 7 char array. It doesn't get 
bigger. You are doing something that is undefined.

You need:
     char result[100];	// big enough not to overflow.
     strcpy (result, "hello ");
     strcat (result, "world");

-Rich



More information about the llvm-dev mailing list