Search code examples
cprintffgets

I can't call function if i don't use printf or dynamic allocation in function. why?


I used Repl compiler.

First issue : If I don't use "printf" function, I can't call fucntion.

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

char *m_strncpy(char *str1, int count) {
    int i;
    char *new_str;
    for (i = 0; i < count; i++) {
        new_str[i] = str1[i];
    }
    return new_str;
}

int main(void)
{

    char str[80];
    char *sp, e;
    int count;

    printf("Enter a string : ");
    fgets(str, sizeof(str) - 1, stdin);
    printf("The number of character : ");
    scanf("%d", &count);
    //printf("Input complete\n");
    sp = m_strncpy(str, count);
    printf("Cut string is %s\n", sp);
    return 0;
}

If I don't use printf("Input complete\n"); The m_strncpy function is not called.

Second issue : If I don't use dynamic allocation in m_strncpy function, I can't call function.

Visual Studio 2017 doesn't allow uninitialization. But Repl compiler allows.

So When I don't initialize char *new_str, it cannot be called. Why??


Solution

  • Your original code exhibits undefined behaviour:

    char *m_strncpy(char *str1, int count) {
        int i;
        char *new_str;                  // new_str is not initialized, it doesn't
                                        //  point anywhere
        for (i = 0; i < count; i++) {
            new_str[i] = str1[i];       // dereferencing an uninitialized pointer is undefined
                                        // behaviour, anything can happen.
        }
        return new_str;
    }
    

    You probably want this:

    char *m_strncpy(char *str1, int count) {
      int i;
      char *new_str = malloc(count + 1);  // +1 for the NUL terminator
    
      if (new_str != NULL)
      {    
        for (i = 0; i < count; i++) {       // copy count first chars
          new_str[i] = str1[i];
        }
    
        new_str[i] = 0;                     // NUL terminate the string
      }
    
      return new_str;
    }