Thread: Why Am I getting dirty data from strncpy

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    1

    Why Am I getting dirty data from strncpy

    Hi All,

    I'm trying to write a very simple program that captures data from stdin and displays it on stdout. Why Am I getting dirty data when the strings are printed ?

    (P.S. I know that using the gets function is highly unrecommended, this program is just for testing purposes)

    Code:
    // MultiLine.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    #define MAX_SIZE 8096
    #define LINE_SIZE 3
    
    void readLines(char *output);
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	char output[LINE_SIZE];
    	readLines(output);
    	getchar();
    
    	return 0;
    }
    
    /**
    ** Lê a entrada através de stdin e de acordo com o tamanho de
    ** cada linha separa as entradas numerando-as de acordo.
    */
    void readLines(char *output) {
    
    	char input[MAX_SIZE];
    
    	int length = 0;
    
    	gets(input);
    	length = strlen(input);
    
    	for(int i = 0; i < length; i+= LINE_SIZE) {
    		strncpy(output, input + i, LINE_SIZE);
    		puts(output);
    	}
    	
    }
    ** dirty ** output
    Code:
    marcos
    mar╠╠╠╠╠8■=
    cos╠╠╠╠╠8■=
    Thank you very much !!

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    LINE_SIZE of 3 is certainly not big enough. Notice how the first three characters of the output are correct and the rest is garbage? Maybe there's a connection
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Read the documentation on strncpy(). It will not null terminate the string when the third argument in less than or equal to the length of the source string.
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. brace-enclosed error
    By jdc18 in forum C++ Programming
    Replies: 53
    Last Post: 05-03-2007, 05:49 PM
  3. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  4. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM
  5. Replies: 1
    Last Post: 07-31-2002, 11:35 AM