How protect dynamic char from being overwritten by second dynamic char?

ぐ巨炮叔叔 提交于 2019-12-11 10:15:32

问题


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

char print_two(char *reg, char *s)
{
    int i, l_s = (int) strlen(s), l_reg = (int) strlen(reg);
    for(i = 0; i < l_reg; i++)
    {
        printf("\n %c \n", reg[i]);
    }
    return 0;
}

int main(void)
{
    char reg;
    printf("Give a rule: ");
    scanf("%s", &reg);

    char s;
    printf("Give a string: ");
    scanf("%s", &s);

    print_two(&reg, &s);
    return 0;
} 

Program start:

Give a rule: qwert
Give a string: asdf
result:
d
q
a
s
d
f

How I can avoid overwrite reg by s?

I tried with realloc, malloc - 0 effect.

Two variables should be dynamic.

Is it possible to do?


user give 55 chars -> array 55

user give 100 chars -> array 100


回答1:


Based on your comments to other answers, if you are ok with using GNU library extensions (mostly on Linux, or on Windows MinGW), you can use %ms in scanf format string, like this:

char *reg = NULL; // set to NULL to get segfault on uninitialized use
printf("Give a rule: ");
scanf("%ms", &reg); // scanf will malloc enough space to reg

// check for null in case scanf failed to read anything for some reason
// could also check return value of scanf, which is number of items it got
if (reg != NULL) {
  // process reg
}

free(reg); // free(NULL) is not an error, it just does nothing
reg = NULL; // set to NULL to get segfault on uninitialized use

Other answers show how to use a buffer with fixed size, which is standard C. Though according to man scanf notes section, %ms might be in a future POSIX standard. GNU also has older %as, but %ms should be preferred when it's supported (ie. in any modern GNU system).




回答2:


scanf("%s", ...) is reading a string from stdin. Your variables reg and s are allocating storage for one character, not for a complete string. You need to change that to char reg[128] for example if your input string can be 128 characters long maximum. To prevent a buffer overflow, you should also consider limiting the length of input scanned by scanf using scanf("%127s", ...).




回答3:


You cannot read a string (multiple characters) into a single character like char s.

You need to reserve more space:

char reg[128], s[128];

Otherwise random things in memory are getting overwritten, and you're getting undefined behavior.



来源:https://stackoverflow.com/questions/14565778/how-protect-dynamic-char-from-being-overwritten-by-second-dynamic-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!