Why won't this run?

This is a discussion on Why won't this run? within the C++ Programming forums, part of the General Programming Boards category; I don't have any errors but when it runs it tells me the program is an illegal operation. #include <stdio.h> ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    5

    Question Why won't this run?

    I don't have any errors but when it runs it tells me the program is an illegal operation.

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

    void insert(char *str, char *substr, int i){

    char buffer[255];
    int x;

    /* copy everything from index to end of str into buffer */
    for(x=0;x<strlen(str)-i; x++){
    buffer[x] = str[x+i];
    }

    /* cut off everything from index to end of str */
    str[i] ='\0';

    /* hook together str + substr + buffer */
    strcat(str,substr);
    strcat(str,buffer);
    }

    int main(int argc, char *argv[])
    {
    char str[255]= "helloworld";
    char substr[25]= "wide";
    int i = 5;


    insert(str,substr,i);
    printf(str);
    return 0;
    }

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    In insert() change

    str[i] ='\0';

    to

    buffer[i] ='\0';
    zen

  3. #3
    Unregistered
    Guest
    buffer and str both need to be null terminated after you cut str up into fragments in order to be used in strcat. Your code puts the null terminator at end of first fragment, str[i], but I think it cuts off the null terminator at end of original str before it can be put into buffer[]. If I'm correct (haven't worked out the details myself) then changing < to <= in terminating condition of for loop may be easiest way to change this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Re-doing a C program to run in Win2000 or XP
    By fifi in forum C Programming
    Replies: 5
    Last Post: 08-17-2007, 05:32 PM
  2. how to run an exe command in c++ and get back the results?
    By mitilkhatoon in forum C++ Programming
    Replies: 5
    Last Post: 09-21-2006, 06:00 PM
  3. calculating the mode
    By bigggame in forum C Programming
    Replies: 10
    Last Post: 06-13-2006, 03:04 AM
  4. How I can Run exe file in C++
    By palang in forum C++ Programming
    Replies: 2
    Last Post: 05-10-2006, 11:55 AM
  5. Replies: 2
    Last Post: 10-29-2002, 03:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21